CTUC103 Unit 02
CTUC103 Unit 02
Class Declaration:
The class declaration describes the type and scope of its members.
The class function definition describes how the class functions are implemented.
Syntax of Class Declaration:
class class-name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
The class is a keyword that specifies that what follows is an abstract data of type
class-name.
The body of the class is enclosed within braces and terminated by a semicolon.
The class body contains the declaration of variables and functions.
These functions and variables are collectively called class members.
Class members are usually grouped into two sections, namely private and public
to denote which members are private and which members are public.
The keywords private and public are known as visibility labels followed by a colon.
The use of private keywords is optional. The default visibility label is private. If
both the labels are missing, then all the members are private. Such a class is
completely hidden from the outside world.
1|Page
The class members that have been declared as private can be accessed only from
within the class.
The public members can be accessed from the outside class also.
The variables declared inside the class are called data members and the functions
are called member functions.
Only the member functions can have access to the private data members and
private functions.
The public members (both data and functions) can be accessed from outside the
class.
The binding of the data and functions together into a single class-type variable is
called Encapsulation.
class simple
{
private:
int no;
char name[10];
public:
void getdata(); //function declaration
void putdata(); //function declaration
};
The class simple contains two private data members and two public member
functions.
The function getdata() can be used to assign values to the variable no and name.
The function putdata() can be used to display their values.
3|Page
Inside the Class Definition:
Another method of defining a member function is to replace the function declaration with
the actual function definition inside the class.
class simple
{
private:
int no;
char name[10];
public:
void getdata() //function definition
{
cin>>no;
cin>>name;
}
void putdata() //function definition
{
cout<<no;
Cout<<name;
}
};
Creating Objects:
Once a class has been declared we can create variables of that type using the class
name. For example, the statement simple s1; creates a variable s1 of type simple.
Thus the variable s1 is called an object of the type simple.
We can declare more than one object in one statement.
For example, simple s1, s2, s3;
The class specification provides only a template and does not create any memory
space for the objects.
Objects can also be created when a class is defined by placing their names
immediately after the closing brace.
class simple
{
private:
int no;
char name[10];
4|Page
public:
void getdata(); //function declaration
void putdata(); //function declaration
}s1, s2, s3;
6|Page
such tasks should have restricted access. We can place these functions in the
private section.
A private member function can only be called by another function that is a member
of its class. An object cannot invoke a private member function using the dot
operator.
class simple
{
private:
int a;
void read(); //private member function
public:
void putdata();
};
If s is an object of simple then s.read(); will not work because the objects cannot
access the private member.
However, the function read() can be called by the function putdata() using the
concept of nesting of member function.
void simple :: putdata()
{
read();
}
7|Page
cout<<"\nEnter marks of 3 subjects : \n";
for(int i=0;i<3;i++)
{
cout<<"\n Marks of subject "<<i+1<<" :: ";
cin>>marks[i];
}
}
void putdata()
{
cout<<"\nRoll No : "<<rno;
cout<<"\nName : "<<name;
cout<<"\nMarks of 3 subjects are :";
for(int i=0;i<3;i++)
{
cout<<"\nMarks of subject "<<i+1<<" :: "<<marks[i];
}
}
};
int main()
{
student s;
s.getdata();
s.putdata();
return 0;
}
The array variable marks[ ] declared as a private member of a class student can
be used in the member functions. We can perform any operation on it.
In the above program getdata() reads the value for roll no, name, and marks of
three subjects. It also calculates the total of three subjects. And finally, it calculates
the percentage.
The putdata() displays the values. Here marks is an integer-type array.
8|Page
This statement is only partly true. The member functions are created and placed
in the memory space only once when they are defined as part of the class
specification.
Since all the objects belonging to that class use the same member functions, no
separate space is allocated for member functions when the objects are created.
Only space for memory variables is allocated separately for each object.
Separate memory locations are necessary because the memory variables will hold
different data values for different objects.
Private Member:
The private members of a class have strict access control. Only the member functions of
the same class can access these members. The private members of a class are inaccessible
outside the class.
Protected Member:
The access control of the protected members is similar to that of private members and
has more significance in inheritance. The member function of the derived class can access
9|Page
the protected data member. Only class member and derived class member can access
protected data, other class member cannot access.
Public Member:
The members of class, which are to be visible (accessible) outside the class, should be
declared in public section. All data members and functions declared in the public section
of the class can be accessed without any restriction from anywhere in the program, either
by function that belongs to the class or by those external to the class.
11 | P a g e
read into an object three times, the count is incremented three times. Since there
is only one copy of the count shared by all three objects, all three output
statements display the value 3.
We can also assign some initial value to the static variable.
Eg. int simple :: count = 5;
Arrays of Objects:
We can have arrays of variables that are of type class. Such variables are called arrays of
objects.
class employee
{
private:
int eno;
char name[10];
public:
void getdata();
void putdata();
};
The identifier employee is a user-defined data type and can be used to create objects that
relate to different categories of employees. Examples are:
employee manager[3]; // array of manager
employee worker[30]; // array of worker
The array manager contains three objects, namely manager[0], manager[1], and
manager[2]of type employee.
13 | P a g e
Similarly, the foreman array contains 25 objects and the worker array contains 30
objects.
Since an array of objects behaves like any other array, we can use the usual array
accessing methods to access individual elements and then the dot member
operator to access the member function.
For example, manager[i].getdata();
will display the data of the ith element of the array manager.
class employee
{
private :
int eno;
char name[10];
public:
void getdata()
{
cout<<"\nEnter Employee No. :: ";
cin>>eno;
cout<<"Enter Name :: ";
cin>>name;
}
void putdata()
{
cout<<"\nRoll No : "<<eno;
cout<<"\nName : "<<name;
}
};
int main()
{
employee e[3];
for(int i=0;i<3;i++)
{
cout<<"\n Details of Manager"<<":"<<i+1;
e[i].getdata();
}
for(i=0;i<3;i++)
{
cout<<"\nMANAGER "<<i+1;
e[i].putdata();
14 | P a g e
}
return 0;
}
Objects as Function Arguments:
Objects may be used as a function argument. This can be done in two ways.
1. A copy of the entire object is passed to the function.
2. Only the address of the object is transferred to the function.
The first method is called pass-by-value. Since a copy of the object is passed to the
function, any changes made to the object inside the function do not affect the object used
to call the function. The second method is called pass-by-reference. When an address of
the object is passed, the called function works directly on the actual object used in the
call. This means that any changes made to the object inside the function will reflect in the
actual object. This method is more efficient because it requires to pass only the address
of the object and not the entire object.
The following program shows the use of objects as function arguments. It performs the
addition of time in the hour and minutes format.
class time
{
private:
int hours;
int minutes;
public:
void getdata(int h, int m)
{
hours=h;
minutes=m;
}
void putdata()
{
cout<<"\tHOURS : "<<hours;
cout<<"\tMINUTES : "<<minutes;
}
void sum(time t1,time t2)
{
minutes=t1.minutes+t2.minutes;
hours=minutes/60;
15 | P a g e
minutes=minutes%60;
hours=hours+t1.hours+t2.hours;
}
};
int main()
{
time t1,t2,t3;
t1.getdata(2,45);
t2.getdata(3,30);
cout<<"\nT1 = ";t1.putdata();
cout<<"\nT2 = ";t2.putdata();
t3.sum(t1,t2);
cout<<"\nT3 = ";
t3.putdata();
return 0;
}
The member function sum() is invoked by the object t3, with the objects t1 and t2 as
arguments. So that it can directly access the hours and minutes variable of t3. But the
members of t1 and t2 can be accessed only by using the dot operator like
(t1.mitues or t2.minutes). Therefore inside the function sum(), the variables hours and
minutes refer to t3 and t1.miutes and t2.minutes refer to t2.
Returning Objects:
A function cannot only receive objects as arguments but also can return them.
The following program shows how an object can be created (within a function) and
returned to another function.
class time
{
private:
int hours;
int minutes;
public:
void getdata(int h,int m)
{
hours=h;
minutes=m;
}
16 | P a g e
void putdata()
{
cout<<"\tHOURS : "<<hours;
cout<<"\tMINUTES : "<<minutes;
}
time sum(time t1, time t2);
};
time time :: sum(time t1,time t2)
{
time t;
t.minutes=t1.minutes+t2.minutes;
t.hours=t.minutes/60;
t.minutes=t.minutes%60;
t.hours=t.hours+t1.hours+t2.hours;
return t;
}
int main()
{
time t1,t2,t3;
t1.getdata(2,45);
t2.getdata(3,30);
cout<<"\nT1 = "<<t1.putdata();
cout<<"\nT2 = "<<t2.putdata();
t3=t3.sum(t1,t2);
cout<<"\nT3 = "<<t3.putdata();
return 0;
}
Friend Function:
The concept of encapsulation and data hiding dictate that non-member functions
should not be allowed to access an object’s private and protected members.
A friend function is a function that can access the private/protected data
members of a class in which it is declared as a friend.
If a keyword friend is placed before any function declared inside the class, that
function is known as friend function. The friend function is declared using the
friend keyword inside the body of the class, But friend function is not a member
function.
17 | P a g e
The friend function definition must be outside the class and do not use the
keyword friend.
Why Friend keyword is used?
It is used to tell the compiler, that it is not a member function of the class. Rather it is a
friend function. Because if you remove the keyword friend, then this function gets
processed by compiler as member function of the class.
How to call Friend function?
Friend function has no object to call it. Because it is not a member function of the class
where it is declared. And to define it, there is no any membership label gets attached while
defining the function. Therefore, to call this function from main() function, just call it as
normal function call.
Characteristics of Friend function:
1. It is not in the scope of the class to which it has been declared as friend.
2. Since it is not in the scope of the class, it cannot be called using the object of that
class.
3. It can be invoked like a normal function without the help of any object.
4. Unlike member functions, it cannot access the member names directly and has to
use an object name and dot membership operator with each member name.(e.g.
A.x).
5. It can be declared either in the public or the private part of a class without affecting
its meaning.
6. Usually, it has the objects as arguments.
Example of Friend Function:
#include<iostream>
using namespace std;
class maths
{
private:
int a,b;
public:
void getdata(int x,int y)
{
a=x;
18 | P a g e
b=y;
}
friend void sum(maths m);
};
void sum(maths m)
{
int ans;
ans=m.a+m.b;
cout<<"\nAddition : "<<ans;
}
int main()
{
maths m;
m.getdata(10,20);
sum(m);
return 0;
}
19 | P a g e
private:
int b;
public:
void getb()
{
b=20;
}
void putb()
{
cout<<"\n\nB IS : "<<b;
}
friend void sum(ABC,XYZ);
};
void sum(ABC p,XYZ q)
{
int c;
c=p.a+q.b;
cout<<"\n\nADDITION IS : "<<c;
}
int main()
{
clrscr();
ABC p;
XYZ q;
p.geta();
q.getb();
p.puta();
q.putb();
sum(p,q);
return 0;
}
Output: ADDITION IS : 30
Constructor:
One of the aims of C++ is to create user-defined data types such as classes that behave
like a built-in types. This means that we should be able to initialize a class type variable
i.e. object when it is declared, much the same way as the initialization of an ordinary
variable. For example,
20 | P a g e
int a=10;
A constructor is a special member function whose task is to initialize the objects of its
class. It is special because its name is the same as the class name. The constructor is
invoked whenever an object of its associated class is created. It is called a constructor
because it constructs the values of the data members of the class.
How the Constructors Are Different From A Member Function?
Constructor can be called automatically when an object is created.
The constructor name is same as of the class.
It does not have the return type.
If the constructor is not specified than the compiler will generate a default
constructor.
A constructor can be declared and defined as follows:
class simple
{
private:
int a, b;
public:
simple (); // constructor declared
void putdata ()
{
cout<<"\an = "<<a;
cout<<"\nab = "<<b;
}
};
simple :: simple() //constructor defined
{
a=10;
b=20;
}
Now, the declaration simple s; not only creates the object s of type simple but also
initializes its data members a and b to 10 and 20 respectively. There is no need to write
any statement to invoke the constructor function.
Characteristics of Constructor:
1. Constructor is declared in the public section.
21 | P a g e
2. Constructor is invoked automatically when the objects are created.
3. Constructors do not have return types, not even void and therefore, and they cannot
return values.
4. Constructor cannot be inherited, though a derived class can call the base class
constructor.
5. Like other C++ functions, constructor can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to constructor’s address.
8. An object with a constructor (or destructor) cannot be used as a member of a union.
9. They make ‘implicit calls’ to the operators new and delete when memory allocation is
required.
Types of Constructor:
1. Default Constructor
2. Parameterized constructor
3. Copy constructor
Default Constructor:
A constructor that accepts no parameters is called the default constructor. In the above
program simple() is a default constructor. It is also known as “Zero Argument/ Zero
Parameter Constructor”.
Similarly, the default constructor for the class A is A :: A(). If no such constructor is
defined, then a compiler supplies a default constructor. Therefore, the statement such as
A a;
invokes the default constructor of the compiler to create the object a.
Example:
#include<iostream>
using namespace std;
class simple
{
private:
int a,b;
22 | P a g e
public:
simple()
{
a=10;
b=20;
}
void putdata()
{
cout<<"\nA IS : "<<a;
cout<<"\nB IS : "<<b;
}
};
int main()
{
simple s;
s.putdata();
return 0;
}
Parameterized Constructors:
The constructors that can take arguments are called parameterized constructors.
class simple
{
private:
int a,b;
public:
simple(int x, int y) // parameterized constructor
{
a=x;
b=y;
}
void putdata()
{
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
}
};
int main()
{
23 | P a g e
simple s(10,20);
s.putdata();
return 0;
}
When a constructor has been parameterized, then we must pass the initial values as
arguments to the constructor function when the object is declared. This can be done in
three ways.
1. By calling the constructor explicitly (clearly called).
2. By calling the constructor implicitly (not clearly).
3. Initialization at the time of declaration with = operator
Implicit call:
The declaration of the object is followed by an argument list enclosed in parentheses. This
method is called shorthand method.
Example:
class simple
{
private:
int a,b;
public:
simple(int x, int y) // parameterized constructor
{
a=x;
b=y;
}
void putdata()
{
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
}
};
int main()
{
simple s(10,20); ;//Implicit Call
s.putdata();
24 | P a g e
return 0;
}
Explicit call:
The declaration of an object is followed by assignment operator; constructor name and
argument list are enclosed in parenthesis.
Example:
#include<iostream>
using namespace std;
class simple
{
private:
int a,b;
public:
simple(int x,int y)
{
a=x;
b=y;
}
void putdata()
{
cout<<"\nA IS : "<<a;
cout<<"\nB IS : "<<b;
}
};
int main()
{
simple s=simple(10,20);//Explicit Call
s.putdata();
return 0;
}
25 | P a g e
class simple
{
private:
int a;
public:
simple(int x)
{
a=x;
}
void putdata()
{
cout<<"\nA IS : "<<a;
}
};
int main()
{
simple s=5;
s.putdata();
return 0;
}
Copy Constructor:
A copy constructor is used to declare and initialize an object from another object. For
example, the statement,
simple s2 (s1);
would create the object s2 and at the same time initialize it to the value of s1.
This can be done by another method as follows.
simple s4 = s1;
The process of initializing through a copy constructor is called copy initialization.
Now consider the following statement
s4 = s2;
This statement will not invoke the copy constructor. However, if s4 and s2 are objects,
this statement is legal and simply assigns the values of s2 to s4, member-to-member.
A reference variable can be used as an argument to the copy constructor. We cannot pass
the argument by value to the copy constructor.
26 | P a g e
When no copy constructor is defined, the compiler supplies its copy constructor.
Example:
class simple
{
private:
int a,b;
public:
simple() // default constructor
{
a=10;
b=20;
}
simple(int x,int y) // parameterized constructor
{
a=x;
b=y;
}
simple(simple &s) // copy constructor
{
a=s.a;
b=s.b;
}
void putdata()
{
cout<<"\nA = "<<a;
cout<<"\nB = "<<b;
}
};
int main()
{
simple s1;
cout<<"OBJECT 1"<< s1.putdata();
simple s2(30,40);
cout<<"\nOBJECT 2"<<s2.putdata();
simple s3(s1);
cout<<"\nOBJECT 3"<<s3.putdata();
simple s4;
s4=s2;
27 | P a g e
cout<<"\nOBJECT 4"<<s4.putdata();
return 0;
}
Output would be as follows:
OBJECT 1 OBJECT 2 OBJECT 3 OBJECT 4
A=10 A=30 A=10 A=30
B=20 B=40 B=20 B=40
Destructors:
A destructor is used to destroy the objects that have been created by a constructor.
A destructor is a member function whose name is the same as the class name but
proceeded by a tilde symbol.
Eg. A destructor for the class simple can be defined as follows:
~ simple ();
A destructor never takes any argument. it does not return any value. It will be invoked
implicitly by the compiler upon exit from the block or function or a program as the case
may be to clean up the storage.
It is good practice to use a destructor in a program because it releases the memory space
for future use.
Characteristics of Destructor:
1. Destructor is also a special member function like constructor.
2. Destructor destroys the memory of class objects’ created by constructor.
30 | P a g e
3. Destructor has the same name as their class name preceded by a tilde (~) symbol.
4. It is not possible to define more than one destructor.
5. Destructors take no arguments. Therefore, destructors cannot be overloaded.
6. Destructor neither requires any returns value.
7. It is automatically called to destroy the memory of object.
8. Destructor release memory space occupied by the objects created by constructor.
9. In destructor, objects are destroyed in the reverse order of an object creation.
class simple
{
private:
static int count;
public:
simple ()
{
count++;
cout<<"\nNumber of Objects created : "<<count;
}
~simple()
{
cout<<"\nNumber of Objects destroyed :"<<count;
count - - ;
}
};
int simple::count;
int main()
{
simple s1,s2,s3,s4;
{
cout<<"\n\n\t BLOCK 1";
simple s5;
}
{
cout<<"\n\n\t BLOCK 2";
simple s6;
}
cout<<"\n\n\t MAIN BLOCK";
return 0;
}
31 | P a g e
As the objects are created and destroyed, they increase and decrease the value of
the count. When a closing brace of a scope is encountered, the destructor is called.
After the first group of objects is created, s5 is created and then it is destroyed.
Then s6 is created and then destroyed. Finally, the rest of the objects are
destroyed.
The objects are destroyed in the reverse order of creation.
Difference between Construcor and Destrctor:
Constructor Destructor
1. Constructor is a special member 1. Constructor is a special member function,
function, which is called automatically which is called automatically when an object
when an object is created. is destroyed
2. Syntax: classname (arguments) 2. Syntax: ~classname()
3. Example: simple() 3. Example: ~simple()
4. Arguments can be passed to the 4. Arguments cannot be passed to the
constructor. destructor.
5. Constructors cannot be virtual. 5. Destructor can be virtual.
6. It has the same name as its class 6. It has the same name as its class but is
prefixed by ~(Tilde) character.
7. A class can have more than one 7. A class cannot have more than one
constructor destructor
8. A constructor can be overloaded. 8. The destructor cannot be overloaded.
9. It is used to allocate the resources to 9. It is used to release all the resources
the object of a class. allocated to the object of a class.
this Keyword:
In C++, this is a special pointer available inside non-static member functions of a
class. It points to the current instance of the class that invoked the member
function.
Key Features of this Keyword:
Accessing the Current Object: This holds the address of the object that called the
member function.
32 | P a g e
Resolving Name Conflicts: Used to differentiate between instance variables and
parameters with the same name.
Returning the Current Object: Enables function chaining by returning the object
itself.
Accessing Members of the Current Object: this->member is equivalent to
member but explicitly refers to the instance variable.
Example:
class simple
{
private:
int a;
int b;
public:
void getdata(int a,int b)
{
this->a = a;
this->b = b;
}
void putdata()
{
cout<<"\nA IS : "<<a; cout<<"\nB IS : "<<b;
}
};
int main()
{
simple s;
s.getdata(10,20);
s.putdata();
return 0;
}
Explanation:
this is a pointer that refers to the current object.
In getdata(int a, int b), local parameters a and b have the same names as class
members.
this->a = a; differentiates the instance variable a from the parameter a.
Similarly, this->b = b; assigns the value to the instance variable b.
33 | P a g e