Você está na página 1de 19

1.what is an array?diff array and structure?

Array:Static memory allocation.


It uses the subscript to access the array elements.
Structure:Dynamic memory allocation.
It uses the dot(.)operator to access the structure
members.
2.Define Array
An array is a simple data structure that arranges elements (values or variables)
of same type in contiguous memory locations that can be individually referenced
by adding an index to a unique identifier. For example the following definition
from C++:
int basicSalary[5]={5000,7000,4000,6000,8000}
defines an array identified by basicSalary and assigns the values on the right h
and side to it. Thus, the array is holding 5000, 7000, 4000, 6000 and 8000 in co
ntiguous memory locations. Each numbers can be retrieved by referring identifier
and index number. For example, basicSalary[0] will refer to 5000, basicSalary[1
] to 7000 and so on.
C++ Program to store 10 salesmen s amount in an array and find out total sale & be
st sales amount.
Well, following is the program to perform as asked in question. I guess you won t
need that heavy commenting in program code. I used them to make it clear what a
particular line of code is doing.
#include<iostream>
/*
A C++ PROGRAM
to store 10 salesmen s amount in an array
and find out total sale & best sales amount.
by: Suresh Khanal http://icttrends.com
in response to: Kigozi Ronald from Makerere University Uganda
*/
int main(){
using namespace std;
//create an array to hold 10 salesman's amount
int amount[10];
int total, best; //Variables to hold total and maximum amount
//Get amounts from user
cout<<"\n Enter sales amount for 10 salesmen\n";
for(int i=0; i<10; i++){
cout<<"\nSales Amount for Salesman No "<<i+1<<" :\t";
cin>>amount[i];
}
cout<<"\n\n Thank you for those data \n\n";
//Calculate Total and maximum
total=0; best=0; //initialize variables
for(int i=0;i<10;i++){
total += amount[i]; //add up all the values
if(best < amount[i]) //check if best holds the maximum
best=amount[i]; //update best if it is not
}
cout<<"\n\n Result \n";
cout<<"\nTotal amount of 10 salesmen's :\t"<<total;
cout<<"\nBest Sales Amount :\t"<<best;
system("Pause");
}
3.benefits of oops:
C++ is an object-oriented programming language, it is designed to allow the
creation and manipulation of objects from the problem domain. Thus, C++ allows p
rogrammers
to operate at a higher level of abstraction. This higher level of abstraction al
lows programmers
to develop software in the language of the problem domain rather than in the lan
guage of the computer. The key to a good abstraction is deep knowledge of the pr
oblem domain. A good abstraction allows users to use an object in a relatively s
afe and predictable manner. It reduces the learning curve by providing a simple
interface described in terms of the user's own vocabulary.
C++ is a multiparadigm language. This allows developers to choose the programmin
g style that is right for the task at hand. For example, a traditional procedura
l style may be appropriate for performing a simple task such as writing the code
within a small member function.
C++ software can be performance and memory efficient. For example, well-designed
, object oriented software is normally comprehensible and therefore amenable to
performance tuning. In addition, C++ has low-level facilities that allow a skill
ed C++ developer to obtain appropriate levels of performance.
C++ is backward compatible with C. This is useful in very large legacy systems w
here the migration to C++ normally occurs a few subsystems at a time rather than
all at once. In particular, C++ backward compatibility makes it relatively inex
pensive to compile C code with C++ compiler.
C++ is a huge language with a very broad base of users. This large user communit
y has led to high quality compilers and other development tools for a wide range
of systems.
There are a few major advantages to using C++:
1. C++ allows expression of abstract ideas
C++ is a third generation language that allows a programmer to express their
ideas at a high level as compared to assembly languages.
2. C++ still allows a programmer to keep low-level control
Even though C++ is a third generation language, it has some of the "feel" of
an assembly language. It allows a programmmer to get down into the low-level wo
rkings and tune as necessary. C++ allows programmers strict control over memory
management.
3. C++ has national standards (ANSI)
C++ is a language with national standards. This is good for many reasons. Co
de written in C++ that conforms to the national standards can be easily integrat
ed with preexisting code. Also, this allows programmers to reuse certain common
libraries, so certain common functions do not need to be written more than once,
and these functions behave the same anywhere they are used.
4. C++ is reusable and object-oriented
C++ is an object-oriented language. This makes programming conceptually easi
er (once the object paradigm has been learned) and allows easy reuse of code, or
parts of code through inheritance.
5. C++ is widely used and taught
C++ is a very widely used programming language. Because of this, there are m
any tools available for C++ programming, and there is a broad base of programmer
s contributing to the C++ "community".
4.Inline function:
The inline function takes the format as a normal function but when it is compile
d it is compiled as inline code. The function is placed separately as inline fun
ction, thus adding readability to the source program. When the program is compil
ed, the code present in function body is replaced in the place of function call.
he general format of inline function is as follows:
inline datatype function_name(arguments)
The keyword inline specified in the above example, designates the function as in
line function. For example, if a programmer wishes to have a function named exfo
rsys with return value as integer and with no arguments as inline it is written
as follows:
inline int exforsys( )
#include <iostream.h>
int exforsys(int);
void main( )
{
int x;
cout << \n Enter the Input Value: ;
cin>>x;
cout<< \n The Output is: << exforsys(x);
}
inline int exforsys(int x1)
{
return 5*x1;
}
5.Access specifiers:
Access specifiers are used to identify access rights for the data and member fun
ctions of the class. There are three main types of access specifiers in C++ prog
ramming language:
* private
* public
* protected
* A private member within a class denotes that only members of the same clas
s have accessibility. The private member is inaccessible from outside the class.
.
* Public members are accessible from outside the class.
.
* A protected access specifier is a stage between private and public access.
If member functions defined in a class are protected, they cannot be accessed f
rom outside the class but can be accessed from the derived class.
When defining access specifiers, the programmer must use the keywords: private,
public or protected when needed, followed by a semicolon and then define the dat
a and member functions under it.

class exforsys
{
private:
int x,y;
public:
void sum()
{

}
};

In the code above, the member x and y are defined as private access specifiers.
The member function sum is defined as a public access specifier.
6.basic caharacteristics of object oriented programming:
Class
Main article: Class (computer science)
A class is a template for an object, a user-defined datatype that contains varia
bles, properties, and methods. A class defines the abstract characteristics of a
thing (object), including its characteristics (its attributes, fields or proper
ties) and the things it can do (behaviors, methods, operations or features). One
might say that a class is a blueprint or factory that describes the nature of s
omething. For example, the class Dog would consist of traits shared by all dogs,
such as breed and fur color (characteristics), and the ability to bark and sit
(behaviors). Classes provide modularity and structure in an object-oriented comp
uter program. A class should typically be recognizable to a non-programmer famil
iar with the problem domain, meaning that the characteristics of the class shoul
d make sense in context. Also, the code for a class should be relatively self-co
ntained (generally using encapsulation). Collectively, the properties and method
s defined by a class are called members.
[edit] Instance
Main article: Instance (computer science)
One can have an instance of a class; the instance is the actual object created a
t run-time. In programmer vernacular, the Lassie object is an instance of the Do
g class. The set of values of the attributes of a particular object is called it
s state. The object consists of state and the behavior that's defined in the obj
ect's classes.
[edit] Method
Main article: Method (computer science)
Method is a set of procedural statements for achieving the desired result. It pe
rforms different kinds of operations on different data types. In a programming l
anguage, methods (sometimes referred to as "functions") are verbs. Lassie, being
a Dog, has the ability to bark. So bark() is one of Lassie's methods. She may h
ave other methods as well, for example sit() or eat() or walk() or save(Timmy).
Within the program, using a method usually affects only one particular object; a
ll Dogs can bark, but you need only one particular dog to do the barking.
[edit] Message passing
Main article: Message passing
"The process by which an object sends data to another object or asks the other o
bject to invoke a method."[13] Also known to some programming languages as inter
facing. For example, the object called Breeder may tell the Lassie object to sit
by passing a "sit" message that invokes Lassie's "sit" method. The syntax varie
s between languages, for example: [Lassie sit] in Objective-C. In Java, code-lev
el message passing corresponds to "method calling". Some dynamic languages use d
ouble-dispatch or multi-dispatch to find and pass messages.
[edit] Inheritance
Main article: Inheritance (object-oriented programming)
Inheritance is a process in which a class inherits all the state and behavior of
another class. This type of relationship is called child-Parent or is-a relatio
nship. "Subclasses" are more specialized versions of a class, which inherit attr
ibutes and behaviors from their parent classes, and can introduce their own.
For example, the class Dog might have sub-classes called Collie, Chihuahua, and
GoldenRetriever. In this case, Lassie would be an instance of the Collie subclas
s. Suppose the Dog class defines a method called bark() and a property called fu
rColor. Each of its sub-classes (Collie, Chihuahua, and GoldenRetriever) will in
herit these members, meaning that the programmer only needs to write the code fo
r them once.
Each subclass can alter its inherited traits. For example, the Collie subclass m
ight specify that the default furColor for a collie is brown-and-white. The Chih
uahua subclass might specify that the bark() method produces a high pitch by def
ault. Subclasses can also add new members. The Chihuahua subclass could add a me
thod called tremble(). So an individual chihuahua instance would use a high-pitc
hed bark() from the Chihuahua subclass, which in turn inherited the usual bark()
from Dog. The chihuahua object would also have the tremble() method, but Lassie
would not, because she is a Collie, not a Chihuahua. In fact, inheritance is an
"a is a" relationship between classes, while instantiation is an "is a" relation
ship between an object and a class: a Collie is a Dog ("a is a"), but Lassie is a
Collie ("is a"). Thus, the object named Lassie has the methods from both classe
s Collie and Dog.
Multiple inheritance is inheritance from more than one ancestor class, neither o
f these ancestors being an ancestor of the other. For example, independent class
es could define Dogs and Cats, and a Chimera object could be created from these
two that inherits all the (multiple) behavior of cats and dogs. This is not alwa
ys supported, as it can be hard to implement.
[edit] Abstraction
Main article: Abstraction (computer science)
Abstraction refers to the act of representing essential features without includi
ng the background details or explanations. Classes use the concept of abstractio
n and are defined as a list of abstract attributes.
[edit] Encapsulation
Main article: Encapsulation (object-oriented programming)
Encapsulation conceals the functional details of a class from objects that send
messages to it.
For example, the Dog class has a bark() method variable, data. The code for the
bark() method defines exactly how a bark happens (e.g., by inhale() and then exh
ale(), at a particular pitch and volume). Timmy, Lassie's friend, however, does
not need to know exactly how she barks. Encapsulation is achieved by specifying
which classes may use the members of an object. The result is that each object e
xposes to any class a certain interface those members accessible to that class.
The reason for encapsulation is to prevent clients of an interface from dependin
g on those parts of the implementation that are likely to change in the future,
thereby allowing those changes to be made more easily, that is, without changes
to clients. For example, an interface can ensure that puppies can only be added
to an object of the class Dog by code in that class. Members are often specified
as public, protected or private, determining whether they are available to all
classes, sub-classes or only the defining class. Some languages go further: Java
uses the default access modifier to restrict access also to classes in the same
package, C# and VB.NET reserve some members to classes in the same assembly usi
ng keywords internal (C#) or Friend (VB.NET). Eiffel and C++ allow one to specif
y which classes may access any member.
[edit] (Subtype) polymorphism
Main article: Subtype polymorphism
Polymorphism allows the programmer to treat derived class members just like thei
r parent class's members. More precisely, Polymorphism in object-oriented progra
mming is the ability of objects belonging to different data types to respond to
calls of methods of the same name, each one according to an appropriate type-spe
cific behavior. One method, or an operator such as +, -, or *, can be abstractly
applied in many different situations. If a Dog is commanded to speak(), this ma
y elicit a bark(). However, if a Pig is commanded to speak(), this may elicit an
oink(). Each subclass overrides the speak() method inherited from the parent cl
ass Animal.
[edit] Decoupling
Decoupling allows for the separation of object interactions from classes and inh
eritance into distinct layers of abstraction. A common use of decoupling is to p
olymorphically decouple the encapsulation,[clarification needed] which is the pr
actice of using reusable code to prevent discrete code modules from interacting
with each other. However, in practice decoupling often involves trade-offs with
regard to which patterns of change to favor. The science of measuring these trad
e-offs in respect to actual change in an objective way is still in its infancy.[
citation needed]
7. virtual function:
A virtual function is a member function that is declared within a base class and
redefined by a derived class. To create virtual function, precede the function s
declaration in the base class with the keyword virtual. When a class containing
virtual function is inherited, the derived class redefines the virtual function
to suit its own needs.
Base class pointer can point to derived class object. In this case, using base c
lass pointer if we call some function which is in both classes, then base class
function is invoked. But if we want to invoke derived class function using base
class pointer, it can be achieved by defining the function as virtual in base cl
ass, this is how virtual functions support runtime polymorphism.
Consider following program code:
Class A
{
int a;
public:
A()
{
a = 1;
}
virtual void show()
{
cout <<a;
}
};
Class B: public A
{
int b;
public:
B()
{
b = 2;
}
virtual void show()
{
cout <<b;
}
};
int main()
{
A *pA;
B oB;
pA = &oB;
pA->show();
return 0;
}
Output is 2 since pA points to object of B and show() is virtual in base class A
.
8.factorial program
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
long factorial(long); // function prototype
int main()
{
int num;
cout << "Input value for factorial: ";
cin >num;
if (num < 0)
{
cout << "Invalid value." << endl
<< "Please input value again: ";
cin >num;
}
else
{
cout << "\nThe factorial of "
<< num
<< " is "
<< factorial(num) << endl;
}
return 0;
}
long factorial(long a)
{
if (a>1)
return a = (a * factorial(a-1));
else
return (1);
}
9.variable types in c++:
In order to use a variable in C++, we must first declare it specifying which dat
a type we want it to be. The syntax to declare a new variable is to write the sp
ecifier of the desired data type (like int, bool, float...) followed by a valid
variable identifier. For example:
1
2

int a;
float mynumber;

These are two valid declarations of variables. The first one declares a variable
of type int with the identifier a. The second one declares a variable of type f
loat with the identifier mynumber. Once declared, the variables a and mynumber c
an be used within the rest of their scope in the program.
If you are going to declare more than one variable of the same type, you can dec
lare all of them in a single statement by separating their identifiers with comm
as. For example:

int a, b, c;

This declares three variables (a, b and c), all of them of type int, and has exa
ctly the same meaning as:
1
2
3

int a;
int b;
int c;

The integer data types char, short, long and int can be either signed or unsigne
d depending on the range of numbers needed to be represented. Signed types can r
epresent both positive and negative values, whereas unsigned types can only repr
esent positive values (and zero). This can be specified by using either the spec
ifier signed or the specifier unsigned before the type name. For example:
1
2

unsigned short int NumberOfSisters;


signed int MyAccountBalance;

By default, if we do not specify either signed or unsigned most compiler setting


s will assume the type to be signed, therefore instead of the second declaration
above we could have written:

int MyAccountBalance;

with exactly the same meaning (with or without the keyword signed)
An exception to this general rule is the char type, which exists by itself and i
s considered a different fundamental data type from signed char and unsigned cha
r, thought to store characters. You should use either signed or unsigned if you
intend to store numerical values in a char-sized variable.
short and long can be used alone as type specifiers. In this case, they refer to
their respective integer fundamental types: short is equivalent to short int an
d long is equivalent to long int. The following two variable declarations are eq
uivalent:
1
2

short Year;
short int Year;

Finally, signed and unsigned may also be used as standalone type specifiers, mea
ning the same as signed int and unsigned int respectively. The following two dec
larations are equivalent:
1
2

unsigned NextYear;
unsigned int NextYear;

// operating with variables


#include <iostream>
using namespace std;
int main ()
{
// declaring variables:
int a, b;
int result;
// process:
a = 5;
b = 2;
a = a + 1;
result = a - b;
// print out the result:
cout << result;
// terminate the program:
return 0;
}

A variable can be either of global or local scope. A global variable is a variab


le declared in the main body of the source code, outside all functions, while a
local variable is one declared within the body of a function or a block.
Global variables can be referred from anywhere in the code, even inside function
s, whenever it is after its declaration.
The scope of local variables is limited to the block enclosed in braces ({}) whe
re they are declared. For example, if they are declared at the beginning of the
body of a function (like in function main) their scope is between its declaratio
n point and the end of that function. In the example above, this means that if a
nother function existed in addition to main, the local variables declared in mai
n could not be accessed from the other function and vice versa.
10.I/O in c++:
Standard Output (cout)
By default, the standard output of a program is the screen, and the C++ stream o
bject defined to access it is cout.
cout is used in conjunction with the insertion operator, which is written as <<
(two "less than" signs).
1
2
3

cout << "Output sentence"; // prints Output sentence on screen


cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

The << operator inserts the data that follows it into the stream preceding it
Standard Input (cin).
The standard input device is usually the keyboard. Handling the standard input i
n C++ is done by applying the overloaded operator of extraction (>>) on the cin
stream. The operator must be followed by the variable that will store the data t
hat is going to be extracted from the stream. For example:
1
2

int age;
cin >> age;

The first statement declares a variable of type int called age, and the second o
ne waits for an input from cin (the keyboard) in order to store it in this integ
er variable.
cin can only process the input from the keyboard once the RETURN key has been pr
essed. Therefore, even if you request a single character, the extraction from ci
n will not process the input until the user presses RETURN after the character h
as been introduced.
You must always consider the type of the variable that you are using as a contai
ner with cin extractions. If you request an integer you will get an integer, if
you request a character you will get a character and if you request a string of
characters you will get a string of characters.
The standard header file <sstream> defines a class called stringstream that allo
ws a string-based object to be treated as a stream. This way we can perform extr
action or insertion operations from/to strings, which is especially useful to co
nvert strings to numerical values and vice versa. For example, if we want to ext
ract an integer from a string we can write:
1
2
3

string mystr ("1204");


int myint;
stringstream(mystr) >> myint;

This declares a string object with a value of "1204", and an int object. Then we
use stringstream's constructor to construct an object of this type from the str
ing object.
11.write a program to find sum of n natural numbers
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int count,i,sum=0;
printf("Enter value of n: ");
scanf("%d",&count);
for(i=1; i<=count; i++)
sum = sum + i;
printf("Sum of %d natural no is: %d",count,sum);
return 0;
}
12.program to find minimum ,maximum and average of n numbers
#include <iostream>
#include <limits> // for INT_MIN AND INT_MAX
using namespace std;
// Function prototypes
int max(int n); // find maximum number among n numbers
int min(int n); // find minimum number among n numbers
int avg(int n); // find average number for n numbers
int main()
{
// Declare variables
int choice, count, num;
count = 0;
int choice;
cout << "Enter a choice (0 = Max, 1 = Min, 2 = Avg, and 3 = Exit): ";
cin >> choice;
while (choice < 0 || choice > 3)
{
cout << "Invalid choice. Try again." << endl;
cout << "Enter a choice (0 = Max, 1 = Min, 2 = Avg, and 3 = Exit): ";
cin >> choice;
}
cout << "How many numbers of input? ";
cin >> num;
if (choice == 0)
{
cout << "Max is " << max(num) << endl;
}
else if (choice == 1)
{
cout << "Min is " << min(num) << endl;
}
else
{
cout << "Avg is " << avg(num) << endl;
}
cout << "Enter a choice (0 = Max, 1 = Min, 2 = Avg, and 3 = Exit): ";
cin >> choice;
}
cout << "Good Bye" << endl;
return 0;
}
// Function descriptions
// Function int max calculates the maximum number of
// n numbers entered by the user. It returns maxNum
// as the maximum number
int max(int n)
{
int count, num1,num2,maxNum;
count = 1;
cout << "Enter " << n << " numbers" << endl;
cin >> num1;
maxNum = num1;
while (count < n)
{
cin >> num2;
if (num2 > maxNum)
{
maxNum = num2;
count++;
}
else
count++;
}
return maxNum;
}
/ Function int min
// int min calculates the minimum number of a set of
// numbers entered by the user. It returns minNum as
// the minimum number. Parameter int n is the
// number of numbers that the user must enter
int max(int n)
{
int count, num1,num2,minum;
count = 1;
cout << "Enter " << n << " numbers" << endl;
cin >> num1;
maxNum = num1;
while (count < n)
{
cin >> num2;
if (num2 < minNum)
{
minNum = num2;
count++;
}
else
count++;
}
return minNum;
}
/ Function int avg calculates the average of n numbers
// entered by the user. It returns avg as the average
// of the entered numbers
int avg(int n)
{
int avg, sum, count, num;
sum = 0;
count = 0;
cout << "Enter " << n << " numbers" << endl;
while (count < n)
{
cin >> num;
sum = sum + num;
count++;
}
avg = sum / n;
return avg;
}
13.program to calculate the volume of a cone
//Starting code.
#include <iostream>
using namespace std;
int main ()
{
//Declares pi, r, h, v.
float r, h, v;
float pi = 3.14159;
//User inputs cone's radius.
cout << "Input cone's radius.";
cin >> r;
//User inputs cone's height.
cout << "Input cone's height.";
cin >> h;
//Caculates the cone's volume.
v = (1.0/3.0) * pi * (r*r) * h;
//Output to screen.
cout << "The volume of the cone is\n\n " << v << "\n";
system ("PAUSE");
return 0;
}
14.write a program to show numbers in descending order
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int ar[100];
int r,t=0,i,j;
for(i=0;i<100;i++)
{
ar[i]=0;
}
printf("\n Enter the range:(less than 100) ");
scanf("%d",&r);
printf("\n Enter the elements of the array:");
for(i=0;i<r;i++)
{
printf("\n Enter element number: %d ",(i+1));
scanf("%d",&ar[i]);
}
for(i=0;i<r;i++)
{
for(j=i;j<r;j++)
{
if(ar[i]>ar[j])
{
t=ar[i];
ar[i]=ar[j];
ar[j]=t;
}
}
}
printf("\n The Sorted array:\n");
for(i=0;i<r;i++)
{
printf("%d ",ar[i]);
}
getch();
}
15.What is the difference between an object and a class?
Classes and objects are separate but related concepts. Every object belongs to
a class and every class contains one or more related objects.
Ø A Class is static. All of the attributes of a class are fixed before, durin
g, and after the execution of a program. The attributes of a class don't change.
Ø The class to which an object belongs is also (usually) static. If a partic
ular object belongs to a certain class at the time that it is created then it al
most certainly will still belong to that class right up until the time that it i
s destroyed.
Ø An Object on the other hand has a limited lifespan. Objects are created an
d eventually destroyed. Also during that lifetime, the attributes of the object
may undergo significant change.
16.Defining Pointer Variables or Pointer:
In order to define pointer variables, the programmer must use the operator denot
ed as * in C++.
The symbol * when placed before a pointer, variable means that it as a pointer t
o.
While defining variables, the data type is placed before it. When the programmer
wants to define the integer variable i it is written:
int i;
A programmer may think that to define pointer variable there is a separate data
type. But this is not the case. There is no separate data type for pointer avail
able. When a programmer defines a pointer variable, he or she can point to integ
er, float, char. The compiler must know the type of data the pointer is pointing
to.
To define pointer variable is as follows:
datatype_of_ variable_pointedto* pointer_varaible;
17.what is nested loop?give example.
Loops may be nested, with one loop sitting in the body of another. The inner loo
p will be executed in full for every execution of the outer loop. This c++ progr
am illustrates writing marks into a matrix using nested for loops.
Illustrates nested for loops.
1: //
2: //Illustrates nested for loops
3:
4: #include <iostream.h>
5:
6: int main()
7: {
8: int rows, columns;
9: char theChar;
10: cout << "How many rows? ";
11: cin >> rows;
12: cout << "How many columns? ";
13: cin >> columns;
14: cout << "What character? ";
15: cin >> theChar;
16: for (int i = 0; i<rows; i++)
17: {
18: for (int j = 0; j<columns; j++)
19: cout << theChar;
20: cout << "\n";
21: }
22: return 0;
23: }
Output: How many rows? 4
How many columns? 12
What character? x
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
xxxxxxxxxxxx
18.what is struct?
The struct keyword defines a structure type and/or a variable of a structure typ
e.
[template-spec] struct [ms-decl-spec] [tag [: base-list ]]
{
member-list
} [declarators];
[struct] tag declarators;
tag
The type name given to the structure. The tag becomes a reserved word within
the scope of the structure. The tag is optional. If omitted, an anonymous struc
ture is defined. For more information, see Anonymous Class Types.
base-list
Optional list of classes or structures this structure will derive its member
s from. See Base Classes for more information. Each base class or structure name
can be preceded by an access specifier (public, private, protected) and the vir
tual keyword. See the member-access table in Controlling Access to Class Members
for more information.
member-list
List of structure members. Refer to Class Members for more information. The
only difference here is that struct is used in place of class.
declarators
Declarator list specifying the names of the class. Declarator lists declare
one or more instances of the structure type. Declarators may include initializer
lists if all data members of the class are public. Initializer lists are common
in structures because data members are public by default. See Overview of Decla
rators for more information.
A structure type is a user-defined composite type. It is composed of fields or m
embers that can have different types.
In C++, a structure is the same as a class except that its members are public by
default.
19.what is enum?
An enumeration is a user-defined type consisting of a set of named constants cal
led enumerators.
For information on CLR enums, see enum class.
Copy
enum [tag] [: type] {enum-list} [declarator]; // for definition of enumerated
type
enum tag declarator; // for declaration of variable of type tag
Parameters
tag
The type name given to the enumeration.
type
The underlying type of the enumeration identifiers. See Remarks.
enum-list
List of the enumerators contained by the enumeration.
declarator
Declarator list specifying the names of the enumeration. See Overview of Dec
larators for more information
20.what is derived data?
1. Derived Data Types: These are the data types which are derived from the fu
ndamental data types. It is further divide into two categories i)Built-In and ii
)User-defined, which are discussed below as seperate topics.
Built-In Derived Data Type
1. Arrays: Arrays refer to a list of finite number of same data types. The da
ta in the array can be accessed by an index number ranging from 0 to n(where n i
s the number of data element it can store). Ex- if arr[3] is an array of int(ege
rs) then the different values in the array can be accessed as shown below. arr[0
], arr[1],arr[2] when we declare an array such as the one sown above then by arr
[3] we mean that we want three elements in the array and hence while accessing a
rr[2] is the last element.
//Program to illustrate arrays
#include<iostream.h>
void main(void)
{
int arr[3];//it will store 3 integer elements
cout<<"enter 3 numbers:";
cin>>arr[0]>>arr[1]>>arr[2];//this statement is same as using three c
in's
cout<<endl;//goto next line
cout<<arr[0]<<arr[1]<<arr[2];
}
2. Pointer: A pointer is a variable that holds the memory address of other va
riable. It is also of different data types, ex- char pointer can store address o
f only char variables, int pointer can store address of int variables and so on.
3. Reference: A reference in the simplest sense is an alias or alternate name
for a previously defined variable.

//Program to illustrate References


#include<iostream.h>
void main(void)
{
int var;
int &refvar=var;//here a reference variable to var is declared rememb
er var was previously declared
var=10;//var is given the value 10
cout<<var<<endl;
refvar=100;//reference variable of var is changed
cout<<var;//but var also gets changed
}
User-Defined Derived Data Types
1. Class: A class is a collection of variables and function under one referen
ce name. it is the way of separating and storing similar data together. Member f
unctions are often the means of accessing, modifying and operating the data memb
ers (i.e. variables). It is one of the most important features of C++ since OOP
is usually implemented through the use of classes.
2. Structure: In C++ structure and class same except for some very minor diff
erences.
3. Union: A union is a memory location shared by two or more different variab
les, generally of different data types. Giving more details here would only conf
use you; I ll leave it for future articles.
4. Enumerations: It can be used to assign names to integer constants.
//Program to illustrate Enumerators
#include<iostream.h>
void main(void)
{
enum type{POOR,GOOD,EXCELLENT};//this is the syntax of enumerator
int var;
var=POOR;//this makes programs more understandable
cout<<var<<endl;
var=GOOD;
cout<<var<<endl;
var=EXCELLENT;
cout<<var;
}
21.what is difference between static binding and dynamic binding?
Static binding is generally more efficient since
1. It has less time & space overhead
2. It also enables method inlining
Dynamic binding is more flexible since it enables developers to
extend the behavior of a system transparently
However, dynamically bound objects are difficult to store in
shared memory

Você também pode gostar