You are on page 1of 33

Introduction of Classes

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.

Difference between Class & Structure:

A structure in C is a collection of similar or dissimilar data types. C++ extends the


reach of structures by allowing the inclusion of even functions within structures.
● The functions defined within a structure have a special relationship with the
structures elements presents within the structure.
● There is another entity in C++ called class that too can hold data and functions.
● Most of the C++ programs use structures to exclusively hold data.
● Most of the C++ programs use classes to hold both data and functions.
● In structures we have to give type for alias names but in case classes no need.
● Objects of classes can call another without dot operator.
● Structure should call its own data with a help of dot operator.

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.

Syntax of Class Declaration:

class <class-name>
{
private:
variable declaration;
function declaration/definition;
public:
variable declaration;
function declaration/definition;
}; // end of the class

The functions and the variables collectively called class members.


The variables declared inside the class are known as data members and functions are
member functions.
The class members are generally grouped under two sections called private and
public. (These are the two access specifiers (or) visibility labels in C++). By default all
members in class is private i.e no external use of it. Where as in public we can access
then even from out side the class.
Note: The binding of data and functions together into a single class type variable is
referred to as encapsulation.
Let’s have an example about class:-
A typical class declaration:-
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
}; // ends with semicolon.

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

3. Accessing Class Members:

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.

Defining a Member Functions

Member function can be defined in two places:


1. Outside the class definition.
2. Inside the class definition.
It is natural that, irrespective of the place of definition the function perform the
same task. Therefore the code for the function body would be identical in both the cases.
But there is difference in function header.

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.

Difference between member function & normal functions:


The important difference between a member function and a normal function is
that a member function incorporates a membership ‘identity label’ in the header. This
label tells the compiler which class the function belongs to.
Syntax on general form of a member function:
return-type class-name : : function-name (arguments declaration)
{
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:

● Several different classes can use the same function name.


● Member functions can access the private data of the class.
● (A non member function can not do so)
● A member function can call another member function directly, without dot
operator.

2 Inside the class definition:

Another method of defining a member function is to replace the function


declaration by the actual function definition inside the class.
Example:-
class item
{
int number;
float cost;
public:
void getdata (int a, float b); // declaration
void putdata ( ) // inline function
{
cout<<number<<”\n”;
cout<<cost<<”\n”;
}
}; //end of the class
Note:
● When a function is defined inside a class, it is treated as an inline function.
● The restrictions and limitations that apply to an inline functions are also
applicable here.
● Generally only small functions are defined inside the class definition.

33
A C++ program with class Access Specifiers

Let’s have a program on class and discussed topics.


#include <iostream.h>
#include<conio.h>
class item
{
int number; // private by default
float cost;
public: // access specifier
void getdata (int a, float b); // prototype declaration
void putdata ( ) // function defined inside class
{
cout<<”number:”<<number<<endl;
cout<<”cost:”<<number<<”\n”;
}
}; //end of the class
// member function definition outside the class
void item :: getdata (int a, float b)
{
number = a; // private variables directly used
cost = b;
}
int main ( ) //main function with return int
{
clrscr( );
item x; //object created
cout<<”\n object x”<< “\n”;
x.getdata(100, 299.5); // call member functions
x.putdata( ) ;

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;
}

Nesting of member functions

We discussed that a member function of a class can be called by an object of that


class using a dot operator. However, there is an exception to this.
A member function can be called by using its name inside another member
function of the same class. This is known as nesting of member functions.
Program: illustrates the nesting of member functions
#include<iostream.h>
class set
{
int m , n;

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:

We can place the member functions in private section. A private member


functions can only be called by another public member functions of its class. Even an
object cannot invoke a private function using the dot-operator.
class sample
{
private:
void fun1 ( ); // private member function
public:
void fun2 ( );
void fun3 ( );
};
If S is an object of sample, then
S.fun1 ( ); //won’t work objects cannot access private members
Is illegal, However, the function fun1( ) can be called by the fun2( ) or fun3( ).
That is,
void sample :: fun2( )
{
fun1( ); // private member function calling
}
Note: A private member functions can be called by using its name in any public member
functions of the same class. No need of any object for this.

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.

common for all objects

member function 1

Memory created when


member function 2 function defined
Object 1 Object 2 Object 3

member variable1 member variable1 member variable1

member variable 2 member variable 2 member variable 2

Static Data Members


33
A data member of a class can be qualified as static. The properties of a static
member variable are similar to that of a C static member variable has certain special
characteristics. These are:-
● It is initialized to zero when the first object of its class is created. No other
initialization is permitted.
● Only one copy of that member is created for the entire class and is shared by all
the objects of that class.
● It is visible only within the class, built lifetime is the entire program.
● The class and scope of the static member variable is defined outside the class
declaration. That is
General form:
return_type class_name :: static_variable;
Program: illustrates the use of static data members.
#include<iostream.h>
#include<conio.h>
class number
{
private:
static int c;
int n;
public:
void normal( )
{
n=0;
}
void count( )
{
c ++;
n++;
cout<<endl<<”value of c=”<<c<<”address of c=”<<(unsigned)&c;

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

value of c= 2 address of c= 1111


value of n= 0 address of n= 3333 //for object B result

value of c= 3 address of c= 1111


value of n= 0 address of n= 4444 //for object C result

Static Member Functions:

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

Arrays with in class:

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

The array manager contains three objects (managers), namely, manager[0],


manager[1] and manager[2] of type employee class. Similarly for foreman’s and
workers.
We can access the members of class through arrays of object with dot operator.
For example:
manager [ i ] . getdata( );
will display the data of the ith element of array manager.
Program:
#include<iostream.h>
#include<conio.h>

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;
}

Objects as Function Arguments

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
};

int sumclasses(A a, B b) //friend function definition


{
return ( a.x + b.y );
}

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

You might also like