Part - A: 1) Objects
Part - A: 1) Objects
Part - A: 1) Objects
1) Objects are instance of a class, that interact with each other at runtime. In OOPs, Objects are decalred at the
end of the class definition or after the "}" braces. They can be of any type based on its declaration. An object can
be considered a "thing" that can perform a set of related activities. The set of activities that
the object performs defines the object's behavior. An object is an instantiation of a class.
In terms of variables, a class would be the type, and an object would be the variable
basically an object is created from a class. We declare objects of a class with exactly the same sort of
declaration that we declare variables of basic types. Following statements declare two objects of class
Box:
Both of the objects Box1 and Box2 will have their own copy of data members
2) Polymorphism is the ability of an object or reference to take many different forms at different instances.
These are of two types one is the "compile time polymorphism" and other one is the "run-time polymorphism".
operator is the same (+), it can perform different actions depending on the type of the operands. This is a
simple example of polymorphism. A few other examples of polymorphism are:
The << and >> operators are bit-shifting operators and they are also used for displaying information on
the screen or for storing values in a variable (the circumstance decides whether they are used to shift
bits or as input and output operators).
The division operator (/) when operating on two integers will produce an integer as the result of
division. But if one of the operands are floating point numbers then the result will also be a floating-
point number.
In this method object is bound to the function call at the compile time itself.
In this method object is bound to the function call only at the run time.
3) :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can
use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration
of the same name in a block or class. For example:
int count = 0;
int main(void) {
int count = 0;
::count = 1; // set global count to 1
count = 2; // set local count to 2
return 0;
}
The declaration of count declared in the main() function hides the integer named count declared in global
namespace scope. The statement ::count = 1 accesses the variable named count declared in global
namespace scope.
You can also use the class scope operator to qualify class names or class member names. If a class member
name is hidden, you can use it by qualifying it with its class name and the class scope operator.
In the following example, the declaration of the variable X hides the class type X, but you can still use the static
class member count by qualifying it with the class type X and the scope resolution operator.
#include <iostream>
using namespace std;
class X
{
public:
static int count;
};
int X::count = 10; // define static data member
int main ()
{
int X = 0; // hides class type X
cout << X::count << endl; // use static member of class X
}
a) Structures
A structure is one or a group of variables considered as a (custom) data type. To create a structure, use
the struct keyword, followed by a name for the object, at least followed by a semi-colon. Therefore,
fundamentally, a structure can be created as:
struct SomeName;
The struct keyword is required. The name of the structure follows the same rules we reviewed for C++
names. Any variable you declare within the body of the structure is referred to as a member of that
structure. For example, a variable such as NumberOfStudents is referred to as a member variable of the
Hand structure
Eg:
struct students
{
char name[10]; //name of student
int SSN; // social security number
char cardtype[10];
float balance;
}
b) Unions
A union is a user-defined data or class type that, at any given time, contains only one object from
its list of members (although that object can be an array or a class type).
c) Enumerations (enum)
Enumerations serve to create data types to contain something different that is not limited to either
numerical or character constants nor to the constants true and false. Its form is the following:
enum model_name {
value1,
value2,
value3,
.
.
} object_name;
d) typedef
C++ allows us to define our own types based on other existing data types. In order to do that we
shall use keyword typedef, whose form is:
typedef existing_type new_type_name ;
5) Static data members: Static data is data that does not change from program load to
program exit.When you create objects belonging to this class, required space is allocated for
holding the integer. Each new object that you create belonging to this class will have its own
version of the integer ‘x’. The keyword ‘static’ helps you to create a single copy for all objects
belonging to the same class. The declaration of a static data member in the member list of a class is not a
definition. You must define the static member outside of the class declaration, in namespace scope. For
example:
class X
{
public:
static int i;
};
int X::i = 0; // definition outside class declaration
Once you define a static data member, it exists even though no objects of the static data member's class exist.
In the above example, no objects of class X exist even though the static data member X::i has been defined.
Static data members of a class in namespace scope have external linkage. The initializer for a static data
member is in the scope of the class declaring the member.
A static data member can be of any type except for void or void qualified with const or volatile. You
cannot declare a static data member as mutable.
6) Destructors :
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class
members when the object is destroyed. A destructor is called for a class object when that object passes out of
scope or is explicitly deleted.
A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For example:
class X {
public:
// Constructor for class X
X();
// Destructor for class X
~X();
};
A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be
declared const, volatile, const volatile or static. A destructor can be declared virtual or pure
virtual
Destructors are implicitly called when an automatic object (a local object that has been declared auto or
register, or not declared as static or extern) or temporary object passes out of scope. They are implicitly
called at program termination for constructed external and static objects. Destructors are invoked when you use
the delete operator for objects created with the new operator
7) Conditional operator ( ? ):
If condition is true the expression will return result1, if it is not it will return result2.
#include <iostream>
using namespace std;
int main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;
}
8) The function call operator in C++ is the () operator, function call operator can accept multiple
arguments of varying types. This particular fact is very significant to us.
For example, if we have a 2-dimensional array class, we cannot overload [] to reference a specific cell
of the array, since [] only takes one value as argument. However, we can overload the () operator,
since it can take multiple arguments, and therefore, we can specify a row and a column as arguments.
In fact, the function call operator is the ONLY overloaded operator that can take variable numbers
and types of arguments. This allows us to use (and misuse) it in a variety of situations.
class IntArray {
private:
int *ptr;
public:
IntArray(size_t size) { ptr = new int[size]; }
~IntArray() { delete [] ptr; }
int& operator[](int index);
int& operator()(int index
9) Multiple Inheritance is a method by which a class is derived from more than one base class. a class inherits
members from more than one class. This is done by simply separating the different base classes
with commas in the derived class declaration.
Example:
#include <iostream.h>
using namespace std;
class Square
{
protected:
int l;
public:
void set_values (int x)
{ l=x;}
};
class CShow
{
public:
void show(int i);
};
Result:
The area of the square is:: 25
In the above example the derived class "Area" is derived from two base classes "Square" and "CShow". This is the
multiple inheritance OOP's concept in C++.
10)Virtual Functions: as the name implies, is something that exists in effect but not in reality. The
concept of virtual function is the same as a function, but it does not really exist although it appears in
needed places in a program. The object-oriented programming language C++ implements the concept of
virtual function as a simple member function, like all member functions of the class. The functionality of
virtual functions can be overridden in its derived classes. The vital reason for having a virtual function is
to implement a different functionality in the derived class.
Virtual Functions are resolved during run-time or dynamic binding. Virtual functions are also
simple member functions. The main difference between a non-virtual C++ member function and
a virtual member function is in the way they are both resolved. A non-virtual C++ member
function is resolved during compile time or static binding. Virtual Functions are resolved during
run-time or dynamic binding
PART - B
Global data items are mainly defined in main program, where local data is defined with the
associated functions.
Many of the functions in the programming language share global data, which is available to all
the functions. The procedural-oriented programming is the traditional approach of programming
for developing application software. High level languages like FORTRAN, COBOL, PASCAL,
BASIC and C are based on the procedure oriented approach and consequently are called
procedural languages.
An enumerated type declares an optional type name and a set of zero or more identifiers that can be used
as values of the type. Each enumerator is a constant whose type is the enumeration. Enum (short for
Enumerated) variable type is a special flavor of a Long type variable. With an Enum, you can specify a
number of valid values for that variable and descriptive constant names for the values of the Enum.
These values are used instead of constants
To create an enumeration requires the use of the keyword enum. The general form of an enumeration type
is:
Here, The enum-name is the enumeration's type name. The list of names is comma separated.
For example, the following code defines an enumeration of colors called colors and the variable c of type
color. Finally, c is assigned the value "blue".
By default, the value of the first name is 0, the second name has the value 1, the third has the value 2, and
so on. But you can give a name a specific value by adding an initializer. For example, in the following
enumeration, green will have the value 5.
Here blue will have a value of 6 because each name will be one greater than the one that precedes it.
Enum FruitType
[_First] = 1
Apple = 1
Orange = 2
Plum = 3
[_Last] = 3
End Enum
Enumerations create new data types to contain something different that is not limited to the values
fundamental data types may take. Its form is the following:
enum enumeration_name {
value1,
value2,
value3,
.
.
} object_names;
For example, we could create a new type of variable called colors_t to store colors with the following
declaration:
enum colors_t {black, blue, green, cyan, red, purple, yellow, white};
Enumerations are type compatible with numeric variables, so their constants are always assigned an
integer numerical value internally. If it is not specified, the integer value equivalent to the first
possible value is equivalent to 0 and the following ones follow a +1 progression. Thus, in our data type
colors_t that we have defined above, black would be equivalent to 0, blue would be equivalent to 1,
green to 2, and so on.
We can explicitly specify an integer value for any of the constant values that our enumerated type can
take. If the constant value that follows it is not given an integer value, it is automatically assumed the
same value as the previous one plus one. For example:
In this case, variable y2k of enumerated type months_t can contain any of the 12 possible values
that go from january to december and that are equivalent to values between 1 and 12 (not between
0 and 11, since we have made january equal to 1).
14) Private members functions :can be accessed only within methods of the class itself. Public
member functions can be accessed through any object of the class. Private functions can only be called
from within public member functions. These functions are also called ‘helper functions’. Usually member
data are made private while functions (or methods) are made public. There might be instances where
you might want to make certain functions private (i.e. you may not want the user to directly access
these functions).
Let’s take the example game program ‘batsman’. After every match the user will enter the
batsman’s new score and then he will have to call two functions to update the batsman’s record
(i.e. the user has to call update_best ( ) and update_worst ( )). It is unnecessary to bother the user
with this kind of a double function call. Why should the user access these two functions directly?
Instead of this, we could define another function called update ( ) which will call update_best ( )
and update_worst ( ). In this way the user needs to only call one function after every match.
The idea of classes is to restrict user access. We don’t want the user to access data or functions
unnecessarily. So, we will make update_best ( ) and update_worst ( ) as private functions while
update ( ) will be a public function.
To illustrate the use of helper functions (private functions)
#include <iostream.h>
class batsman
{
private:
int player_number;
int best_score,worst_score;
void update_best(int);
void update_worst(int);
public:
batsman(int n, int b, int w) //constructor
{
player_number=n;
best_score=b;
worst_score=w;
}
void update(int);
void display( );
};
void batsman::update(int x)
{
update_best(x); //private function is called
update_worst(x);
cout<<"\n\nThe scores have been updated\n";
}
void batsman::display( )
{
cout<<"\nHighest score : "<<best_score;
cout<<"\nLowest score : "<<worst_score;
}
int main( )
{
batsman b(1, 140, 20);
cout<<"The scores before the match is ";
b.display( );
b.update(180);
cout<<"\nAfter this match the scores are ";
b.display( );
return 0;
}
#include <iostream.h>
class mm
{
protected:
int rollno;
public:
void get_num(int a)
{ rollno = a; }
void put_num()
{ cout << "Roll Number Is:"<< rollno << "\n"; }
};
class marks : public mm
{
protected:
int sub1;
int sub2;
public:
void get_marks(int x,int y)
{
sub1 = x;
sub2 = y;
}
void put_marks(void)
{
cout << "Subject 1:" << sub1 << "\n";
cout << "Subject 2:" << sub2 << "\n";
}
};
class extra
{
protected:
float e;
public:
void get_extra(float s)
{e=s;}
void put_extra(void)
{ cout << "Extra Score::" << e << "\n";}
};
int main()
{
res std1;
std1.get_num(10);
std1.get_marks(10,20);
std1.get_extra(33.12);
std1.disp();
return 0;
}
Result:
Roll Number Is: 10
Subject 1: 10
Subject 2: 20
Extra score:33.12
Total: 63.12
In the above example the derived class "res" uses the function "put_num()". Here the "put_num()"
function is derived first to class "marks". Then it is deriived and used in class "res". This is an
example of "multilevel inheritance-OOP's concept". But the class "extra" is inherited a single time in
the class "res", an example for "Single Inheritance". Since this code uses both "multilevel" and
"single" inheritence it is an example of "Hybrid Inheritance
The this pointer is a pointer accessible only within the nonstatic member functions of a class, struct, or union
type. It points to the object for which the member function is called. Static member functions do not have a this
pointerThe keyword this identifies a special type of pointer. Suppose that you create an object named x of
class A, and class A has a nonstatic member function f(). If you call the function x.f(), the keyword this in
the body of f() stores the address of x. You cannot declare the this pointer or make assignments to it.
this
this->member-identifier
#include <iostream>
using namespace std;
class MyClass {
int data;
public:
MyClass() {data=100;};
void Print1();
void Print2();
};
int main()
{
MyClass a;
a.Print1();
a.Print2();
OUTPUT:
100
My address = 0012FF88
100
4
PART -C
1. Object
2. Classes
3. Inheritance
4. Dynamic Binding
5. Polymorphism
6. Message passing
7. Encapsulation
Objects are instance of a class, that interact with each other at runtime. In OOPs, Objects are decalred at the end
of the class definition or after the "}" braces. They can be of any type based on its declaration
Example:
#include <iostream.h>
class Cube
{
public:
int cub( val)
{
r = val*val*val;
return r;
}
void show()
{
cout << "The cube is::" << r;
}
private:
int val, r;
}x;
void main()
{
Cube x;
x.cub(2);
x.show();
}
Result:
The cbe is :: 8
In the above example "x" is an object of the class "Cube" used to access the functions inside the class
Classes has the data and its associated function wrapped in it. Classes are also known as a collection of similar
objects or objects of same type. In the OOPs concept the variables declared inside a class are known as "Data
Members" and the functions are known as "Member Functions".
Syntax:
class class-name
{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};
Example:
#include <iostream.h>
class Square
{
public:
int area( side)
{
a =side*side;
return a;
}
void show()
{cout << "The area is::" << a;}
private:
int side, a;
}x;
void main()
{
Square x;
x.area(10);
x.show();
}
Result:
The area is:: 100
In the above OOPs example the class "square" has functions "area" and "show" to calculate the area of the square
and to display the area. so all these are objects that are related to the class "Square".
Inheritance is a method by which new classes are created or derived from the existing classes. Using Inheritance
some qualities of the base classes are added to the newly derived class, apart from its own features The advantage
of using "Inheritance" is due to the reusability of classes in multiple derived classes. The ":" operator is used for
inherting a class.
Single inheritance
Multiple inheritance
Hierarchial inheritance
Multilevel inheritance
Hybrid inheritance
Example:
#include <iostream.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{ val=a;}
};
class Square: public Value
{
public:
int square()
{ return (val*val); }
};
int main ()
{
Square sq;
sq.set_values (5);
cout << "The square of 5 is::" << sq.square() << endl;
return 0;
}
Result:
The square of 5 is:: 25
In the above example the object "val" of class "Value" is inherited in the derived class "Square".
Dynamic Binding refers to linking a procedure call to the code that will be executed only at run time. The code
associated with the procedure in not known until the program is executed, which is also known as late binding.
Example:
#include <iostream.h>
int Square(int x)
{ return x*x; }
int Cube(int x)
{ return x*x*x; }
int main()
{
int x =10;
int choice;
do
{
cout << "Enter 0 for square value, 1 for cube value: ";
cin >> choice;
} while (choice < 0 || choice > 1);
Result:
Enter 0 for square value, 1 for cube value:0
The result is:100
In the above OOPs example the functions "Square" and "Cube" are called only at runtime based on the value given
for "choice". Then a pointer "ptr" is used to call the appropriate function to get the result.
Polymorphism is the ability of an object or reference to take many different forms at different instances. These are of
two types one is the "compile time polymorphism" and other one is the "run-time polymorphism".
In this method object is bound to the function call at the compile time itself.
Run time polymorphism:
In this method object is bound to the function call only at the run time.
Example:
#include <iostream.h>
class Value
{
protected:
int val;
public:
void set_values (int a)
{ val=a;}
};
class Cube: public Value
{
public:
int cube()
{ return (val*val*val); }
};
int main () {
Cube cb;
Value * ptr = &cb;
ptr->set_values (10);
cout << "The cube of 10 is::" << cb.cube() << endl;
return 0;
}
Result:
The cube of 10 is:: 1000
In the above OOPs example "Cube" is a derived class of "Value". To implement polymorphism a pointer "ptr" is used
to reference to the members of the class "Cube". This is an example for "Compile time polymorphism."
Message Passing is nothing but sending and receving of information by the objects same as people exchange
information. So this helps in building systems that simulate real life. Following are the basic steps in message
passing.
In OOPs, Message Passing involves specifying the name of objects, the name of the function, and the information to
be sent
Encapsulation is the method of combining the data and functions inside a class. This hides the data from being
accessed from outside a class directly, only through the functions inside the class is able to access the information.
This is also known as "Data Abstraction", as it gives a clear separation between properties of data type and the
associated implementation details. There are two types, they are "function abstraction" and "data abstraction".
Functions that can be used without knowing how its implemented is function abstraction. Data abstraction is using
data without knowing how the data is stored.
Example:
#include <iostream.h>
class Add
{
private:
int x,y,r;
public:
int Addition(int x, int y)
{
r= x+y;
return r;
}
void show( )
{ cout << "The sum is::" << r << "\n";}
}s;
void main()
{
Add s;
s.Addition(10, 4);
s.show();
}
Result:
The sum is:: 14
In the above encapsulation example the integer values "x,y,r" of the class "Add" can be accessed only through the
function "Addition". These integer values are encapsulated inside the class "Add".
Overloaded operators are functions with special names the keyword operator followed by the symbol for the
operator being defined. Like any other function, an overloaded operator has a return type and a parameter
list.
single operator can take up several functions as desired by programmers depending on the argument
taken by the operator by using the operator overloading facility.
operator overloading helps the programmer to define a new functionality for the existing
operator. This is done by using the keyword operator.
Sample Code
1. return_type classname :: operator operator_symbol(argument)
2. {
3. ...
4. statements;
5. }
operator overloading is defined as a member function by making use of the keyword operator.
In the above:
Overloading of I/O :
#include <iostream>
using namespace std;
class Distance
{
private:
int feet; // 0 to infinite
int inches; // 0 to 12
public:
// required constructors
Distance(){
feet = 0;
inches = 0;
}
Distance(int f, int i){
feet = f;
inches = i;
}
friend ostream &operator<<( ostream &output,
const Distance &D )
{
output << "F : " << D.feet << " I : " << D.inches;
return output;
}
return 0;
}
OUTPUT:
$./a.out
Enter the value of object :
70
10
First Distance : F : 11 I : 10
Second Distance :F : 5 I : 11
Third Distance :F : 70 I :
Pointer Overloading:
class triple {
public:
triple(int a, int b, int c) { i = a; j = b; k = c; }
void print() { cout << "\ni = " << i << ", j = "
<< j << ", k = " << k; }
private:
int i, j, k;
};
class t_ptr {
public:
t_ptr(bool f, triple* p) { access = f; ptr = p; }
triple* operator ->();
private:
bool access;
triple* ptr;
};
put( ) and get( ) functions: The function put( ) writes a single character to the associated
stream. Similarly, the function get( ) reads a single character from the associated stream.
# include <iostream.h>
# include <conio.h>
# include <fstream.h>
# include <string.h>
void main( )
{
char string[80];
cout << "Enter a string \n";
cin >> string;
int len = strlen (string);
fstream file;
file.open("TEXT", ios::in|ios::out);
for(int j= 0; j < len; j++)
file.put (string[j]);
file.seekg(0);
char ch;
while(file)
{
file.get(ch);
cout << ch; }
getch();
}
Note that we have used an fstream object to open the file. Since an fstream object can
handle both the input and output simultaneously, we have opened the file in ios::in|ios::out
mode.After writing the file,we want to read the entire file and display its contents. Since the
file pointer has already moved to the end of the file, we must bring it back to the start of
the file. This is done by the statement
file.seekg(0);
write( ) and read( ) functions: The functions write( ) and read( ), unlike the functions
put( ) and get( ),handle the data in binary form. This means that the values are stored in
the disk file in the same format in which they are stored in the internal memory. An int
takes four bytes to store its value in the binary form, irrespective of its size. But a 4-digit int
will take four bytes to store it in the character form.The binary format is more accurate for
storing the numbers, as they are stored in the exact internal representation.There are no
conversions while saving the data and therefore saving is much faster.The binary input and
output functions take the following form:
These functions take two arguments. The first is the address of the variable v, and the
second is the length of that variable in bytes. The address of the variable must be cast to
type char* (i.e. pointer to character type). Program illustrates how these two functions are
used to save an array of float numbers and then recover them for display on the screen.
# include <iostream.h>
# include <iomanip.h>
# include <conio.h>
#include <fstream.h>
#include <string.h>
const char* filename = "BINARY" ;
void main ( ) {
height[j]=0;
ifstream infile(filename);
infile.read((char *)& height, sizeof(height));
for(int j=0; j<4; j++)
{
cout.setf(ios::showpoint);
cout << setw(10) << setprecision(2)
<< height[j];
}
infile.close( );
getch();
}
Reading and writing a class object: The class objects are the central elements of C++
programming, it is quite natural that the language supports features for writing to and
reading from the disk files objects directly.The binary input and output functions read( ) and
write( ) are designed to do exactly this job.These functions handle the entire structure of an
object as a single unit, using the computer's internal representation of data.For instance,
the function write( ) copies a class object from memory bytes by byte with no conversion.
One important point to remember is that only data members are written to the disk file and
the member functions are not. Program illustrates how class objects can be written to and
read from the disk files. The length of the object is obtained using the sizeof operator.
# include <iostream.h>
# include <conio.h>
#include <fstream.h>
#include <iomanip.h>
class inventory
{
char name[10];
int code;
float cost;
public:
void readdata(void);
void writedata(void);
};
void main( )
{
inventory item[3];
fstream file;
file.open("stockdat", ios::in|ios::out);
cout << "Enter details for three items \n";
for(int j=0;j< 3;j++){
item[j].readdata( );
file.write((char *) &item[j],sizeof(item[j]));
}
cout <<"output is :\n";
for( j=0; j< 3;j++){
file.read((char *) &item[j],sizeof(item[j]));
item[j].writedata( );
}
file.close( );
getch();
}
The program uses for loop for reading and writing data. This is possible because we know
the exact number of objects in the file. In case, the length of the file is not known,we can
determine the file-size in terms of objects with the help of the file pointer functions and use
it in the for loop or we may use while(file) test approach to decide the end of the file.
put( ) and get( ) functions:The function put( ) writes a single character to the associated
stream.Similarly,the function get( ) reads a single character from the associated stream.
# include <iostream.h>
# include <conio.h>
# include<fstream.h>
# include<string.h>
void main( )
{
char string[80];
file.seekg(0);
char ch;
while(file)
{
file.get(ch);
cout<<ch;
}
getch();
Note that we have used an fstream object to open the file. Since an fstream object can
handle both the input and output simultaneously, we have opened the file in ios::in|ios::out
mode. After writing the file, we want to read the entire file and display its contents. Since
the file pointer has already moved to the end of the file, we must bring it back to the start
of the file. This is done by the statement
file.seekg(0);
The main( ) program creates a group object called grp. Such an object holds the data for 20
person structures. The program then displays all the persons in the group, and asks the
user to enter data for an additional person. The user can enter as many persons as desired.
Before terminating, the program again displays the data for all persons. Besides the array of
persons, group contains four member functions and a count of how many of the object
spaces are actually in use. The first function, addData( ) , is the only one that acts on a
single person structure. It prompts the user for data, and adds a person object to the end of
the array. The other member functions act on the array as a whole. The showData( )
function displays the data for each of the count structures stored in the array in memory.
The diskIn( )function checks to see that the GROUP.DAT file ,exists. If so, it opens the file
and reads its entire contents into the array parr in single statement.The infile object will
return a zero value if the GROUP.DAT file does not exist, so That the statement
if( infile )
can be used to determine whether an attempt should be made to read the file The
diskOut( ) function writes the entire array parr from memory to the disk file GROUP.DAT. In
the read( ) and write( ) stream functions the address of the object to be read or written is
this and its size is sizeof(* this). The this pointer holds the address of the object of which
diskOut( ) and diskIn( ) are members, so we can use it to read or write the entire object.