Escolar Documentos
Profissional Documentos
Cultura Documentos
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
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;
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
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.