Professional Documents
Culture Documents
The most important feature of C++ is the “class”. Its significance is highlighted
by the fact. A class is an extension of the idea of structure used in C. It is a new way of
creating and implementing a user-defined type (data). We shall discuss the concept of
class by first reviewing the traditional structures found in C and then the ways in which
classes can be designed, implemented and applied.
Specifying a Class:
1. Class Definition:
A class is a way to bind the data and its associated function together. It allows the
data to be hidden, if necessary from external user. When defining a class, we are creating
a new abstract data type that can be treated like any other built is data type.
A Class can be specified in two parts:-
1. Class declaration.
2. Class function definitions.
33
● The class declaration describes the type and scope of its member.
● The class function definitions describe how the class functions are implemented.
class <class-name>
{
private:
variable declaration;
function declaration/definition;
public:
variable declaration;
function declaration/definition;
}; // end of the class
33
2. Creating Objects:
Once a class has been declared, we can create variable of that type by class name.
The class variables of class are called as objects.
The declaration of an object is similar to that of a variable of any basic type. And
the necessary memory space is allocated to an object at this stage.
Syntax:
classname variablename;
This variablename is nothing but object of type classname.
Example:
item x;
We may also declare more than one object in one statement.
item x , y , z ;
Objects can also be created when a class is defined by placing their names
immediately after the closing brace, as we do in case of structures.
Example:
class item
{
---------------------
---------------------
---------------------
}x,y,z; // here x , y , z are objects
The private data of a class can be accessed only through the member functions of
that class.
The following is the format for calling a member function:
object_name . function_name ( actual_arguments);
33
Example:
class item
{
int number; // variable declaration
float cost; // private by default
public:
void getdata (int a, float b); // functions declaration
void putdata (void); // using prototype
};
Accessing members:
item x; // x is object
x.getdata( 10, 25.5 );
similarly
x.putdata( );
Note: 1) Remember a member function can be invoked only by using an object(of the
same class).
2) The statement like getdata( 20, 15.5 ) has no meaning.
Similarly x.number=100 is also illegal. Although x is an object of the type
item to which number belongs to private member can be accessed only
through a member function and not by the object directly.
33
1 Outside the class definition:
Member functions that are declared inside a class have to be defined separately
outside the class. Their definitions like are as normal functions. They should have a
function header and a function body.
Note:- The scope of the function is restricted to the class name specified in the header
line.
: : is called the scope resolution operator.
Example:
void item :: getdata (int a, float b) // member function definition
{
number = a;
cost = b;
}
void item :: putdata ( )
{
cout<<”number:”<<number<<”\n”;
cout<<”cost:”<<cost<<”\n”;
}
33
Characteristics of member function:
33
A C++ program with class Access Specifiers
33
item y; // another object is created
cout<<”\n object y”<<”\n”;
y.getdata (200, 45.75);
y.putdata( );
return 0; // return zero statement
} // end of main
Output:
object x
number:100
cost:299.5
object y
number:200
cost:175.5
Inline Functions
C++ proposes a new feature called inline function. It is a function that is
expanded in line when it is invoked.
That is, the compiler replaces the function call with the corresponding function
code(something similar to macros expansion).
It is easy to make a function inline, prefix the keyword inline to the function
definition. All inline functions must be defined before they are called.
The inline functions are defined as follows:
inline function_header
{
function body
}
Some of the situations where inline expansion may not work are:
● If functions contains a loop, a switch, or a goto.
● For functions not returning values, if a return statement exists.
● If functions contain static variables.
● If functions are recursive
33
Note: Inline expansion makes a program run faster because the overhead of a function
call and return is eliminated.
Program: illustrates the use of inline function.
#include<iostream.h>
inline int mul( int x, int y)
{
return ( x * y);
}
inline float div(float p, float q)
{
return ( p / q);
}
int main( )
{
int a=4, b=2;
float c=8.45,d=5.35;
cout<<”The mul result:”<<mul( a , b )<<endl;
cout<<”The div result:”<<div( c , d )<<endl;
return 0;
}
Output:
The mul result: 8
The div result: 1.5794
33
Making an outside function inline:
We can make a outside defined member function as a inline function just using
the qualifier inline in header line of function definition.
Example:
class item
{
int number;
float cost;
public:
void getdata (int a , float b); // declaration
};
inline void item :: getdata (int a, float b)
{
number = a,
cost = b;
}
33
public:
void input( );
void display( );
int largest( );
};
int set :: largest( )
{
if( m >= n )
return (m);
else
return (n);
}
void set :: input( )
{
cout<< “Input values of m and n”<<endl;
cin>> m >> n;
}
void set :: display( )
{
cout<< “largest value=”<<largest( ); // calling member function
}
int main( )
{
set A; // A is object
A.input( );
A.display( );
return 0;
}
Output:
Input values of m and n 25 18
Largest value = 25
33
Accessing private member functions:
33
Memory Allocation for Objects
● Memory space for objects is allocated when they are declared and not when the
class is specified.
● Only declaration of a class does not allocate memory to the class data members,
when an object is declared memory is reserved for data members only and not for
member functions.
● Memory is allocated to member functions only once when a class is declared.
● All objects of a class access the same memory location where member functions
are stored.
● Separate memory location for the objects ate essential, because the data members
(or) member variables will hold different data values for different objects.
member function 1
33
cout<<endl<<”value of n=”<<n<<”address of n=”<<(unsigned)&n;
}
}; // end of class
int number :: c;//we can also initialize the value like int number :: c=(0 or anynumber);
int main( ) //by default zero.
{
number A , B , C ;
clrscr();
A.normal();
B.normal();
C.normal();
A.count();
B.count();
C.count();
getch();
return 0;
}
Output:
value of c= 1 address of c= 1111
value of n= 0 address of n= 2222 // for object A result
33
Like static member variable, we can also have static member function.
Characteristics of member functions
● A Static function can have access to only other static members declared in
the same class.
● A static member function can be called using the class name.
Class-name:: function-name;
Let’s have an example illustrating the above topics.
#include <iostream.h>
class test
{
int code;
static int count; // static member variable
public:
void setcode( )
{
code = ++count; // in this static data member is incrementing i.e count
}
void showcode( )
{
cout<<”object number :”<< code <<endl ;
}
static void showcount ( ) // static member function
{
cout<<”count:”<<count<<endl ;//in this only static members can access
}
}; //end of the class
int test : : count; // definition of static data member
int main ( )
{
33
test t1 , t2;
t1.setcode ( );
t2.setcode ( );
test : : showcount ( );// accessing static function
test t3;
t3.setcode( );
test : : showcount( );
t1.showcode ( );
t2.showcode ( );
t3.showcode ( );
return (0);
} // end of int main
Output:
count : 2
count : 3
object number : 1
object number : 2
object number : 3
The arrays can be used as member variables in a class. the following class
definition is valid.
class sample
{
accessspecifiers:
datatype array_name[size]; // this is declaration of array in class
};
Arrays of Objects
33
We know that an array can be of any data type including struct. Similarly, we can
also have arrays of variables that are of the type class. Such variables are called arrays of
objects. Consider the following class
class employee
{
char name[30];
float age;
public:
void getdata();
void putdata();
};
The identifier employee is a user-defined data type(class) and can be used to create
objects that related to different categories of the employees.
Example:
employee manager[ 3 ]; // array of manager object
employee foreman[ 10 ]; // array of foreman object
employee worker[ 30 ]; // array of worker object
class Student
33
{
char name[ 30 ];
int rno;
float sgpa;
public:
void getdata( );
void putdata( );
};
void Student : : getdata( )
{
cout<<”Enter name:”;
cin>>name;
cout<<”Enter roll no:”;
cin>>rno;
cout<<”Enter SGPA:”;
cin>>sgpa;
}
void Student : : putdata ( )
{
cout<<”Name:”<<name<<endl;
cout<<”Roll No:”<<rno<<endl;
cout<<”SGPA:”<<sgpa;
}
int main( )
{
clrscr( );
Student secc4[ 66 ] ;
cout<<”Reading the details of c4-section students:”<<endl;
for( int i=0 ; i<66 ; i++ )
{
secc4[ i ] . getdata( ) ;
33
}
cout<<”Displaying the details of c4-section students:”<<endl;
for( int i=0 ;i<66 ; i++ )
{
secc4[ i ] . putdata( );
}
getch( );
return 0;
}
Like any other type, an object may be used as function argument. This can be in two
ways.
● A copy of the entire object is passed to the function.
● Only the address of the object is transferred to the function.
The first method is called pass by value and the other is called pass by reference. When
an address of the object that any changes made to the object directly on the actual object
used in the call. This means pass by reference method is more efficient since it requires to
pass only the address of object and not the entire object.
Example:
#inlude<iostream.h>
class Time
{
int hours;
int minutes;
public:
void gettime (int h, int m)
{
hours = h;
33
minutes = m;
}
void puttime ( )
{
cout<<hours<<”hours and”;
cout<<minutes<<”minutes”<<endl;
}
void sum ( Time , Time ); //declaration with object as arguments
};
void Time :: sum ( Time t1, Time t2) // t1,t2 are objects
{
minutes = t1.minutes + t2.minutes;
hours = minutes/60;
minutes = minutes %60;
hours = hours + t1.hours + t2.hours;
}
int main( )
{
Time t1 , t2 , t3 ; // Three objects
t1.gettime(19, 45);
t2.gettime(3,30);
t3.sum( t1 , t2 );
cout <<”T1=”;
t1.puttime( ); //display t1
cout <<”T2=”;
t2.puttime( ); //display t2
cout <<”T3=”;
t3.puttime( ); //display t3
return 0 ;
} // end of the main
33
Returning Objects:
A function can not only receive objects as arguments but also can return then.
Example:
#inlcude<iostream.h> // x + i y form
class complex
{
float x ; // real part
float y ; // imaginary part
public:
void input ( float real , float img )
{
x = real ;
y = img ;
}
complex sum ( complex , complex ); // function returning object
void show ( complex );
};
complex complex : : sum (complex c1 , complex c2)
{
complex c3; // objects c3 is created
c3.x = c1.x+c2.x; // x = real, y = ing
c3.y = c1.y+c2.y;
return ( c3 ); // returns objects c3
}
void complex : : show ( complex c)
{
cout<< c.x << “ + i “ << c.y <<endl;
}
33
int main( )
{
complex A , B , C ; // Three objects
A.input( 3.1 , 5.65 );
B.input( 2.75 , 1.2 );
C = C.sum( A , B ); // function calling and it is returning object
//and that object assigned to C object.
cout<<”A=”;
A.show( A );
cout<<”B=”;
B.show( B );
cout<<”C=”;
C.show( C );
return 0;
}
Default Arguments
● C++ has the ability to pass its own default arguments within a functional call, if
not represented.
● The default arguments are used if the calling function does not supply the
argument values when function is called.
● The missing arguments should always be trailing arguments(right to left).
● Default arguments are signed only in functions prototype(declaration) and should
not be repeated in the function definition.
● Whenever the function is called, if the function defines default arguments then it
will goes to prototype and then jumps to function definition.
● Default values specified when the function is declared, and must be initialize the
variables from right to left.
● We can not provide initialization of variables in the middle of the argument list.
33
Some examples of function declaration with default values are:
int mul( int i , int j=5 , int k=10 ); //legal
int mul( int i=5 , int j ); //illegal
int mul( int i=3, int j, int k=6 ); //illegal
int mul( int i=2,int j=7, int k=10 ); //legal
Program: Write a program to define function sum( ) with default arguments.
# include<iostream.h>
int main( )
{
int sum( int a, int b=10, int c=15, int d=20); // function declration
int a=2;
int b=3;
int c=4;
int d=5;
cout<<”Sum=”<<sum( a, b, c, d );
cout<<”\nSum=”<<sum( a, b, c );
cout<<”\nSum=”<<sum( a, b );
cout<<”\nSum=”<<sum( a );
cout<<”\nSum=”<<sum( a, c, d );
return 0;
}
int sum( int i, int j, int k, int l )
{
return ( i+j+k+l );
}
Output:
Sum=14
Sum=29
Sum=40
Sum=47
Sum=32
33
Const Arguments
The constant variable can be declared using const keyword. It makes variable
value stable. The constant variable should be initialized while declaring.
Syntax:
a) const <variablename> = value;
b) <functionname> ( const <type>*<variablename> );
Example:
int const x; //invalid
int const x=5; //valid
The const modifier assigns an initial value to a variable that cannot be changed later by
program.
In C++, an argument to a function can be declared as const as shown below.
int function1( const char*p );
int function2( const string &s);
The const tells the compiler that the function should not modify the argument. The
compiler will generate an error when this condition is violated. This type of declaration is
significant only when we pass arguments by reference or pointers.
Function Overloading
● It is possible in C++ to use the same function name for multiple functions.
● Defining multiple functions with same name is known as function overloading
or function polymorphism. Polymorphism means a function having many forms.
● The overloaded functions must be differing in no of arguments (or) types of
arguments (or) order of argument list.
33
Principles of function overloading:
● If two functions have the similar type in its number of arguments with data types,
but the return types are different then those functions cannot be overloaded.
Example:
int sum( int , int );
float sum( int , int );
functions cannot be overloaded.
● The functions return type may be similar (or) void, but it must be different in
number of arguments or arguments data types.
Example1:
sum( int , int );
sum( float , float);
In the above example number of arguments is same in both the functions, but data
types are different. Hence the above functions can be overloaded.
Example2:
sum( int , int );
sum( int , int ,int );
In the above example data types of arguments are same in both the functions, but
number of arguments is different. Hence the above functions can be overloaded.
Program: illustrate the function overloading. (Without Class).
#include<iostream.h>
#include<conio.h>
int add( int x , int y) //two integer arguments
{
return x+y ;
}
float add( int x , float y) //one int and float arguments
{
return x+y;
}
33
float add( float x , int y) //one float and int arguments
{
return x+y;
}
float add( float x , float y) //two float arguments
{
return x+y;
}
int main( )
{
int a , b;
float c , d;
cout<<”\n Enter any two integers:”;
cin>> a >> b;
cout<<”\n Enter any two floats:”;
cin>> c >> d;
cout<<”\n Calling the add (int,int):=”;
cout<< add ( a , b );
cout<<”\n Calling the add (int,float):=”;
cout<< add( a , c );
cout<<”\n Calling the add (float,int):=”<< add( c , b );
cout<<”\n Calling the add (float,float):=”<< add( c , d );
return 0;
}
Output:
Enter any two integers: 2 5
Enter any two floats: 3.5 7.4
Calling the add (int,int):= 7
Calling the add (int,float):= 5.5
Calling the add (float,int):= 8.5
Calling the add (float,float):= 10.9
33
Program: illustrate the function overloading. (With Class).
#include<iostream.h>
#include<conio.h>
class funover
{
int i ;
float f;
public:
int sqr( int x )
{
i = x*x;
return i ;
}
float sqr( float y )
{
f = y*y;
return f ;
}
}; //end of class
int main( )
{
clrscr( );
funover F ; // object created
int a=5;
float b=2.5;
cout<<”Square of integer no:”<< F.sqr( a ) ;
cout<<”\n Square of float no:”<< F.sqr( b );
return 0;
} //end of main()
Output:
Square of integer no: 25
Square of float no: 6.25
33
Friend Functions:
● Private member functions can’t be accessed from outside the class, i.e. a non
number function can’t have an access to the private data of a class.
● In real world programming there could be a situation where we would like two
classes to share a particular function.
● In C++ common function can be made friendly with the both classes, which
allows the function to have access to private data of these classes.
● These types of functions need not be members of any of these classes
To make an outside function a “friendly” to a class
Syntax:
class <classname>
{
member;
public:
members;
friend void <function name > ( argument );
};
● The function declaration should be preceded by the keyword friend.
● Function definition doesn’t use either the keyword friend (or) scope resolution
(::) operation
● A function can declared as friend in any no.of classes. Though it is non member
function it has all access rights of private members of classes.
Characteristics of Friend Functions:
● Not in the scope of class to which it’s declared as friend.
● Since it is not in the scope of the class, it can’t be called using the object of that
class.
● It can be invoked like normal function without the help of any object.
● Can’t access the members directly, it has to use an object name and dot operator .
● Can be declared either in public (or) private of class
33
● Have objects as arguments.
● Called by reference
● In this a pointer to the address of object is passed and the called function directly
works on actual object used in the call
● The above method can be used to alter the values of private members of class
Example-1: Program to illustrate Friend Functions:
#include<iostream.h>
class A
{
int x;
public:
void accept( )
{
cout<<”Enter x:”;
cin>>x;
}
friend int add_objects(A ,A ); //decleration of friend function
};
int add_objects(Aa1,Aa2) //definition of friend function
{
return (a1.x+a2.x);
}
void main
{
A a1, a2;
A1.accept ();
A2.accept ();
cout<<”Sum of both values”<<add_objects(a1,a2);
}
Output: Enter x : 10 Enter x : 25 Sum of both values : 35
33
Example-2: Develop a program to calculate the sum of integers of two classes using
friend sum functions.
#include<iostream.h>
class B; // forward declaration
class A
{
int x;
public:
void accept()
{
cout<< “Enter X :”;
cin>>x;
}
friend int sumclasses(A , B); //friend function declaration
}; //end of class
class B
{
int y;
public:
void accept( )
{
cout<<”Enter Y :”;
cin>>y;
}
friend int sumclasses(A , B);// friend function in two classes
};
33
int main( )
{
A a;
B b;
a.accept( );
b.accept( );
cout<<”Sum of both classes:”<<sumclasses (a, b); //friend function calling
return (0);
}
Output: Enter X : 4 Enter Y : 5
Sum of both classes : 9
Friend Classes
● When all the functions need to access another class in such a situation we can
declare an entire class as friend class.
● The friend is not transferable (or) inheritable one to another.
● Declaring class A to be a friend of class B doesn’t mean that class B is also friend
to class A. i.e. friendship is not exchangeable.
Example:
#include<iostream.h>
class A
{
int x;
friend class B; // Be ready to friendship with B & it is for Class A
public: void accept( )
{
cout<<Enter X :”;
cin>>x;
}
};
33
class B
{
int y;
public:
void accept( )
{
cout << “Enter Y :”;
cin>>y;
}
void show(A a ) //It is getting data from class A
{
cout<<”Value of no. of class A “<<a.x;
cout<<”Value of no. of class B”<<y;
cout<<”Sum of two no’s”<<a.x+y;
}
};
int main( )
{
A a;
a.accept ();
B b;
b.accept( );
b.show(a); //Here “show” is in Class B but we are calling with Object of A
return 0;
}
33