Classes and Objects Classes
Classes and Objects Classes
This mechanism of binding data and functions that operate on that data is call data encapsulation.
This mechanism of hiding data of a class from the outside world (other classes) so that any access to it either
intentionally or unintentionally can’t modify the data is called data hiding.
Class Declaration:
A class specification has two parts:
(I) Class Declaration
(II) Class Function definitions
The class declaration describes the type and scope of its member. The class definitions describe how the class
functions are implemented. The general form of class declaration is
private: \\ by private we mean that members can be accessed only from within the class i.e
member data can be accessed by the member functions.
data members;
member functions;
protected: \\ by protected we mean that members can be accessed only by member functions
and friends of that class.
data members;
member functions;
public: \\ by public we mean that members can be accessed outside class also.
data members;
member functions;
};
Creating Object:
An object is an instance of a class. In general a class is a user defined data type, while an object is an instance
of an class.
ObjectName . DataMember
Name of Object Member Access Specifier( Dot operator ) Data member of Class
Syntax for accessing data members of a class
Name of Object Member Access Specifier( Dot operator ) Data member of Class
S1.getdata(129,704.5 ); assign value 129 to rollno and 704.5 to marks of object S1.
S1.display( ); will display value of data members.
2
3
Constructors
class classname
{
private: ……
public:
classname( Parameter list ); //constructor declaration
};
Default Constructor: The constructors that can take no arguments are called default constructors.
e.g. time t1,t2;
class time
{
private:
int hr,min;
public:
time( ); //default constructor
};
Parameterized Constructor: The constructors that can take arguments are called parameterized
constructors.
3
4
This is done by passing argument to constructor function when the objects are created. This can be done in two
ways.
1. By calling the constructor implicitly (Implicit calling) time t1(11,11);
2. By calling the constructor explicitly (Explicit calling) time t1 = time(11,11);
Copy Constructor:
A copy constructor takes a reference to its own class as parameter i.e. a constructor having a reference to an
instance of its own class as an argument is known as copy constructor.
Copy constructors are used in following situations:
The initialization of an object by another object of the same class.
Return of objects as function value.
Stating the object as by value parameters of the function.
time t3(t1);
where time is a user defined class name and ptr is a pointer to a class object time.
Destructors
A destructor is a special member function which is used to destroy the object that has been created by
constructor.
4
5
void main ( )
{
sample S;
cout<<endl<<”Main terminated”;
}
The output is
Object is born
Main terminated
Object dies
The output shows when the constructor and destructor are called.
The destructor is called for an object when it reaches the end of its scope.
5
6
Member Functions
In C++, the member functions can be declared outside the class declaration. i.e. declare function prototype
within the body of a class and then define it outside the body of a class. This is done by using scope resolution
operator ( : : ). It acts as an identity label to inform the compiler, the class to which the function belongs. The
general syntax is
fuction body
In other method of function definition is to replace the function declaration by the actual function definition inside
the class. All the member functions defined within the body of class are treated as inline by default.
6
7
Inline Functions:
An inline member function is like a macro, any call to this function in a program is replaced by the function itself.
This is called inline expansion. By this the overhead occurred in the transfer of control by the function call and
function return statements are cut down.
C++ treats all the member functions defined within a class as inline and those defined outside as non-inline.
Member functions defined outside the class declaration can be made inline by prefixing the keyword inline.
#include<iostream.h>
#include<conio.h> void main()
class sum {
{ Sum s;
private: clrscr( );
int a; s.add( );
int b;
public: getch( );
}
inline void add( );
};
inline void sum : : add()
{
cout<<”\n SUM2 =”<<a+b;
}
Friend Functions:
Friend function is a special mechanism for letting non member functions access private data. A friend function
possesses the following characteristics:
1. The scope of the friend function is not limited to class in which it has been declared friend.
2. A friend function can be invoked like a normal function without the help of any object.
3. Unlike the class member functions, it can’t access the member name directly & has to use an object name
and dot operator with each member name to access the private and public members.
4. It can be declared either in private or public part of class without affecting its meaning.
7
8
class time
{ void put ( time t ) //object passed to friend function
private: {
int hr,min; cout<<”\n time is ”<< t.hr <<” : ”t.min<<”hrs”;
public: }
void main( )
time( ) : hr(0), min(0) //default constructor {
time t1;
void get( ); clrscr( );
Friend Classes
A friend class in C++ can access the "private" and "protected" members of the class in which it
is declared as a friend. We can also declare all the member functions of one class as the friend
of another class. In such cases, the class is called a friend class. This can be specified as
follows:
class A
{
……
8
9
Program illustrating use of static data member and static member function
class data void main( )
{ {
private: clrscr( );
static int count; data : : counter( );
public: data d1,d2;
data( ) data : : counter( );
{ count++; } }
static void counter( ) OUTPUT:
{ Total objects = 0
cout<<”\n Total objects = “<<count; Total objects = 2
}
};
data : : count = 0;
9
10
To declare a constant member function, place the const keyword after the closing parenthesis of the argument
list. The const keyword is required in both the declaration and the definition. The constant member function
cannot modify any data members or call any member functions that aren’t constant.
d1.NonConstFun ( );
d1. ConstFun( );
}
OUTPUT:
Enter value of x = 11
Value of x = 11
10
11
An overloaded declaration is a declaration that had been declared with the same name as a
previously declared declaration in the same scope, except that both declarations have different
arguments and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate
definition to use by comparing the argument types you used to call the function or operator with the
parameter types specified in the definitions. The process of selecting the most appropriate
overloaded function or operator is called overload resolution.
Function overloading
Function overloading is a concept that allows multiple functions to share the same name with
different argument type i.e. function definition can have multiple forms.
You can have multiple definitions for the same function name in the same scope. The definition of
the function must differ from each other by the types and/or the number of arguments in the
argument list. You cannot overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types:
void print(double f) }
{ Output:
cout << "\n Printing float: " << f << endl; Printing int: 5
} Printing float: 500.263
};
11
12
Operator overloading,
The mechanism of giving new meaning to an operator is know as operator overloading.
We can redefine or overload most of the built-in operators available in C++. Thus a programmer
can use operators with user-defined types as well.
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.
1. Operator overloading cannot be used to change the way operator works on built-in types. Operator
overloading only allows to redefine the meaning of operator for user-defined types.
2. There are two operators assignment operator(=) and address operator(&) which does not need to be
overloaded. Because these two operators are already overloaded in C++ library. For example: If
obj1 and obj2 are two objects of same class then, you can use code obj1=obj2; without overloading
= operator. This code will copy the contents object of obj2 to obj1. Similarly, you can use address
operator directly without overloading which will return the address of object in memory.
3. Not all operators in C++ language can be overloaded. The operators that cannot be overloaded in
C++ are ::(scope resolution), .(member selection), .*(member selection through pointer to function)
and ?:(ternary operator).
12
13
13
14
Binary operator overloading Binary operators are the operators that work on two
operand.
class point void main ( )
{ {
private: point p1(11,12,13);
int x, y, z; clrscr( );
public: p1.display ( );
point( ):x(0),y(0),z(0) -p1;
{ } p1.display ( );
point (int a, int b, int c) getch( );
{x=a;y=b; z=c; } }
void display ( ) Output:
{ cout<<” \n point = ”<< x <<” : “ << y <<” : “ << z; } Point = 11,12,13
Point = -11,-12,-13
point operator + ( point p )
{
point temp;
temp.x = x + p.x;
temp.y = y + p.y;
temp.z = z + p.z;
return temp;
}
};
Constructor overloading
In C++, Constructor is automatically called when object (instance of class) create.It is special
member function of the class. Which constructor has arguments that’s called Parameterized
Constructor.
14
15
15
16
16
17
Polymorphism can be defined as the ability to use the same name for two or more related but
technically different tasks. The main advantage of Polymorphism is that it reduces complexity by allowing same
name to perform different tasks.
Polymorphism
Functional Operator
Virtual Functions
Overloading Overloading
Compile Time: The information is known to compiler at the compile time and therefore compiler is able to
select the appropriate function for a particular call at compile time itself. This is called early binding or static
binding or static linking. It is also known as compile time polymorphism because early binding simply
means that an object is bound to its function call at compile time.
Run Time: The information is known at the run time and therefore compiler is able to select the appropriate
function for a particular call at run time itself. This is called late binding or dynamic binding or dynamic linking.
Since the function is linked with particular object after compilation i.e., during program execution, the
process is called late binding.
Virtual Functions
A virtual function is that one that does not really exist but it appears real in some parts of program. These
functions are defined in base class in the public section and they provide mechanism by which the derived class
can override it. These functions are bound dynamically.
18
19
Virtual Destructors
Virtual Destructors member function is invoked to free memory automatically. But the destructor of the derived
class is not invoked to free the memory which was allocated by the constructor of the derived class. It is
because the destructor is non virtual and the message will not reach the destructor under late binding.
So it is better to have destructor as virtual and virtual destructors are essential in program to free the
memory space effectively using late binding.
19