Ref 1
Ref 1
Classes & Objects: Introduction, Class Specification, examples, Class Objects, Access
members, defining member functions, data hiding, constructors, destructors,
parameterized constructors, static data members, static member functions, scope resolution
operator, Passing Objects to Functions, Returning Objects, Object Assignment
Pointers and dynamic memory allocation: Pointers, Pointer as function arguments, Dynamic
Allocation Operators new and delete, Initializing Allocated Memory, Initializing Allocated
Memory, Allocating Arrays, Allocating Objects
Data 1…
Data 2…
func1()….
func2()…..
• Class is a user defined data types. Once a class been declared, the programmer can
create a number of objects associated with that class.
• Defining objects of a class data type is known as a class instantiation.
• Functions declared within the class as known as member functions or methods and the
variables declared within the class are data members or member variables.
• By default, functions and data declared within the class are private to that class and can
be accessed only through the member functions of that class. That is, the data and the
functions those operate on the data and strongly binded together providing the data
security(encapsulation mechanism).
• By specifying the access specifier as public we can make data and functions to be
accessible outside the class.
2.3 Examples
• A typical class declaration would look like:
class Student {
};
class Student
{
char name[10];
int age;
public:
void read();
} s1, s2 ; //object creation during class declaration
• After declaration of the class, if a programmer wants to create objects, he/she can use
class name as a data type name as variable name. the general form
• Class_name v1, v2, v3..,
• For example:
• Student s1, s2;
• Now, s1 and s2 are the objects of a class student. Both s1 and s2 have their own physical
memory locations (i.e memory address) separately. That is, the objects will havet heir
own copies of member variables of the class. Hence, every object is different from the
other object of the same class.
2.5 Accessing Members
• The public members of class can be accessed through the dot( ) operator.
• The general form:
[Link];
Example:
class Demo {
public:
void show( ) // by default show is an inline function.
{ cout << “Member function inside class”; }
};
int main( )
{
Demo ob;
[Link]();
}
o Example
class Demo
{
public:
void show( );
};
void Demo::show( ) //defining member function outside
{ cout << “Member function out Side class”; }
int main( )
{
Demo ob;
[Link]( );
}
o Member function defined outside class can be made inline using keyword
inline.
o Syntax:
o Example
inline void Demo :: show ()
{
cout << “Member function outSide class”;
}
o Function show( ) is a member of Demo class.
• Access Specifiers
o Access modifiers are used to implement the concept of Data Hiding. There are
3 types of access modifiers available in C++:
§ Private
§ Public
§ Protected
• Private
• Public
o Public members can be accessed by the objects of the same class from any
other class or the function outside the class.
o Member functions are generally defined as public.
• Protected
o Class member declared as protected are inaccessible outside the class but they
can be accessed by any subclass (derived class) of that class.
Example:
class Point { int main( )
private: int x, y; {
public: Point P1;
void setData( ) P1.x = 20; //Invalid <private data cant be accessed>
{ X = 5, y = 6;} [Link]();
[Link]();
void showData( ) { }
cout << “X = “ << x;
cout << “Y = “ << y;}
};
Destructors
• Definition: Destructor is a member function which is invoked automatically when the
object goes out of its scope
• Properties of Destructor
o Destructor has the same name as the class.
o Destructor is automatically called when the object is out of scope.
o Destructor is used to destroy an object.
o Destructor has no return types. (Not even void)
o Destructor cannot be overloaded. We can have only one destructor per class.
o Destructor does not have any parameters.
Output:
Inside constructor
Hello
Inside Destructor
}
top++;
st[top]=item;
}
void stack::pop(){
if(top==-1) //check for stack underflow
{
cout<<”Stack is empty”;
return;
}
cout<<”Deleted item is”<<st[top]<<endl;
top--;
}
int main()
{
stack s1, s2; //create two stack objects Output:
[Link](11); Stack initialized
[Link](12); Stack initialized
[Link](21); Deleted element is 12
[Link](22); Deleted element is 22
Deleted element is 21
[Link](); Stack destroyed
[Link]() Stack destroyed
[Link]();
}
Thus, we can say that the same member variable of the class will have different values for
different objects. And each object is a separate instance of a class independent of another
object.
• The programmer has not defined any constructor for the above class. Still the compiler
would have provided default constructor, that looks like:
Test () { }
• Thus, when an object gets created for the class with no visible constructor, the compiler
creates and calls this default constructor indicates no action is to be taken when the
object is created.
Note: Whenever the programmer declares any type of constructor, then the compiler will not
add default constructor.
• Here, the constructor has no arguments, but defines some action, which needs to be
taken care when an object gets created.
Parameterized Constructor
• Definition: A Constructor with parameters is a parametrized constructor.
• Constructor are meant for automatic initialization. If it is required to initialize a variable
of an object to a user-specified value, that value can be passed to the constructor as a
parameter.
• Example for parameterised constructor
class Test{
int a,b;
public:
Test(int x, int y){
A=x;
B=y;
}
void disp(){
cout<<”a =”<<a<<”\t b=”<<b;
}
};
int main(){
Test t1(2,3);
Test t2(10,20);
[Link](); //prints 2 4
[Link](); // prints 10 20
}
• In main function creates an object t1 and also calls the constructor with two arguments
t1(2,3) The values 2 and 3 are passed to respective variables x and y and then they
are assigned to member variable a and b. Similarly for object t2.
Note: If a constructor has only one parameter, the initial value can be passed using an
assignment operator.
class Test{
int a;
public:
Test(int x)
{
A=x;
}
void disp(){
cout<<”a =”<<a;
}
};
int main()
{
Test t1(3); //value is provided as an argument
Test t2 =10; // value provided using assignment operator
[Link]();
[Link]();
}
Copy Constructor
• Definition: A Constructor used to create an object using an existing object is known as
copy constructor.
• A copy constructor has the following general function prototype:
• The copy constructor takes only one argument, which is a reference to the object of
same class.
t1, ob t2
Ob.a is copied
a to t2.a a
10
10
p p
1300 1500
Unnamed
int on heap
Value Is copied
Unnamed int on 5
heap 5
1500
1300
• Memory map for the objects t1 and t2 when copy constructor is used
• In the above program, when the statement-
Test t2=t1;
• Is executed, the copy constructor is called. The object t1 itself is passed as a parameter
to copy constructor. The above statement is understood by the compiler as-
[Link](t1)
• That is, t2 is an object calling a constructor Test with the argument t1. Hence copy
constructor parameter may internally seem to be.
Test &ob=t1;
• Thus, ob will act as a reference to the objectt1. That is, ob is just an alias name to t1
and it represents same physical object.
Demo()
{
p=new int;
}
Demo(Demo &d)
{
a = d.a;
b = d.b;
p = new int;
*p = *(d.p);
}
void setdata(int x,int y,int z)
{
a=x;
b=y;
*p=z;
}
void showdata()
{
std::cout << "value of a is : " <<a<< std::endl;
std::cout << "value of b is : " <<b<< std::endl;
std::cout << "value of *p is : " <<*p<< std::endl;
}
};
int main()
{
Demo d1;
[Link](4,5,7);
Demo d2 = d1;
[Link]();
return 0;
}
Output:
value of a is : 4
value of b is : 5
value of *p is : 7
class sample{
static int index;
int count;
public:
sample(){
index++;
count++;
}
void display(){
cout<<”Index=”<<index;
cout<<”count=”<<count;
}
};
int sample :: index=0; //actual definition of static data
int main(){
Sample s1; Output
Index=1
[Link](); Count=4567 //garbage value
Sample s2; Index=2
[Link](); Count=1234 //garbage value
Sample s3; Index =3
[Link](); Count=1544 //garbage value
}
When an object s1 is created, the static member variable i.e index gets incremented through
the constructor. But, as count is an ordinary integer variable. The objects s1, s2 and s3
will get separate copies of it and since it has not been initialized, they will have some garbage
value. Therefore when we call the function display() for s1, the value of index is 1 and
the value for count is some garbage value. When we declare one more object s2 of the class
sample, then again the constructor gets called incrementing the value of index. Similarly, for
the object s3 too.
s1 s2 s3
index
As memory map depicts, there will be different copies of the variable count for each object
separately. Whereas, the static variable index is being shared by all the objects. Thus,
uniqueness of each object of the same class can only be determined by non -static members are
common for all objects.
Note:
1. A static data members is useful when all objects of one class must share a common item
of information.
2. A static data member is available only within a class, but it continues to live till end of
the program execution.
3. The static data members are defined outside the class. Defining it inside the class
declaration would violate the concept that a class is just a blueprint and does not set
aside any memory.
4. If you declare static variable inside the class and forgot to define it using the scope
resolution operator(::) outside the class, then the compiler may pass it. But linking error
will occur stating that “you are trying to reference an undeclared external variable”
class sample{
static int index;
public:
sample(){
index++;
}
static int display(){ //static function
return index;
}
};
int sample :: index=0; //actual definition of static data
int main(){
cout<<”Now there are”<<sample::display()<<”objects”;
sample s1, s2;
cout<<”Now there are”<<sample::display()<<”objects”;
sample s3;
cout<<”Now there are”<<sample::display()<<”objects”;
}
Output:
Now there are 0 objects
Now there are 2 objects
Now there are 3 objects
This program is used to count the number of objects created for a particular class. In this case
display() is a static member function that can access only static data member i.e. index.
Before creating any objects, the value of index is zero. If two objects s1 and s2 are created,
then since the constructor gets called twice, the index value will be 2 and so on.
#include<iostream>
using namespace std;
int a=20;
int main()
{ int a=30; //local declaration
cout<<a; //prints local variable a as 10
cout<<(::a); //access global variable ‘a’ using :: and it prints 20
}
Consider class Test in the program It contains a member variables a and a constructor
to initialize that variable and a disp() function. There is an independent function fun()
which takes an object of the class Test as an argument. In the main() function an object
ob is created and then passed to fun(). Note that here, the function parameter t takes
the object ob as a value (i.e call by value method). Within fun(), using the object t, the
member function disp() is called. So output of this program is 5.
class Test{
int a;
Public:
Test() { }
Test(int x){
a=x;
}
void disp(){
cout<<a;
}
};
Test myfun(){ //function whose return type is class Test
test ob(10); //function creation and parameterized constructor call
return ob; //returning an object
}
int main(){
Test obj; // default constructor call
obj=myfun(); //function returns an object and store in obj
[Link](); // call member function
}
In function myfun(), an object ob is created and its state has been decided by the
member variable a. Then, it is being returned to the calling funcition main(). Where
object obj receives a copy of ob. Remember, the object obj in the main() function
was just created using default constructor and was not been initialized. Now as obj
receives the copy of ob, the value of member variable a inside obj also gets the value 10.
Hence the output of the program would be 10
class Test{
int a;
public:
void put(int x){
a=x;
}
int get(){
return a;
}
};
int main(){
Test ob1,ob2;
[Link](25);
ob2=ob1;
cout<<”The data in ob2 is: <<[Link]();
}
Output
The data in ob2 is 25
2.16 Pointers
• Pointers is a derived datatype that refers to another variable or object.
• Syntax
datatype *pointer_variable;
• Properties of pointers/Advantage
o Pointer provide direct access to memory
o Pointers save memory space in call-by-reference
o Memory can be dynamically allocated or de-allocated using pointers
o Pointers has different applications like: file handling, stack, linked list, tress
etc..,
o Pointer are type compatibles.
#include <iostream>
using namespace std;
void swap (double *x, double *y)
{ double temp;
temp = *x;
*x = *y;
*y = temp;
}
int main ()
{ double a = 100, b = 20.40;
swap (&a, &b);
Pointer to objects
• to refer the address of a variable of any data type, we can have a pointer of that type.
Similarly, we can have pointers to store the address of object. To access the pointer
members of the class, we will use arrow(->) operator instead of dot( . ) operator.
• Just like any other variable, pointer arithmetic holds good for object pointers. That is
increment/decrement by one in pointer points to next/previous object in the array.
• When there is a public member variable in a class, we can have a pointer to that and
access the same using pointer directly.
#include<iostream>
using namespace std;
class myclass
{
int a;
public:
myclass(){
a=0;
}
myclass(int n){
a=n;
}
int get(){ return a;}
};
main()
{ int k;
myclass ob1(100), *ptr1,*ptr2;
myclass ob2[3]={1,2,3};
ptr1=&ob1;
ptr2=&ob2;
cout<<ptr->get();
for(k=0;k<3;k++){
cout<<ptr2->get();
pt2++;}
}
this keyword
• A pointer to current object is known as this pointer
Or
• When an object invokes a member function, a pointer to that object is created and
passed to the function automatically. Such pointer is known as this pointer.
• Each object gets its own copy of data members and all objects share a single copy of
member functions.
#include <iostream>
using namespace std;
class Emp {
public:
int id; //data member (also instance variable)
string name; //data member(also instance variable)
float salary;
Emp(int id, string name, float salary)
{
this->id = id;
this->name = name;
this->salary = salary;
1. }
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main() {
Emp e1 = Emp(101,"Sonoo",890000); //creating an object of Employee
Emp e2 = Emp(102,"Nakul",59000); //creating an object of Employee
[Link]();
[Link]();
return 0;
2. }
Output:
101 Sonoo 890000
102 Nakul 59000
Here, when the constructor is called for object e1,then inside constructor, this indicates the
pointer to [Link] the constructor is called for e2, then this refers to the pointer to e2.
required the same can be de-allocated and returned to OS. This is known as dynamic
memory de-allocation.
• In c++, dynamic memory allocation is achieved with the help of new operator.
• Syntax:
pointer_variable = new data_type;
• Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in
data type including array or any user defined data types including structure and class.
• Example:.
Delete operator
• Since it is programmer’s responsibility to deallocate dynamically allocated memory,
programmers are provided delete operator by C++ language.
• Syntax:
• Here, pointer-variable is the pointer that points to the data object created by new.
Examples:
delete p;
Example:
int *p = new int(25);
float *q = new float(75.25);
#include<iostream>
using namespace std; ß--------4 bytes---------à
int main(){ <- 4 bytes. ->
int *p =new int; p
*p=10; 10
cout<<”p=”<<*p; 1500
1500
delete p;
}
Output:
Dynamic memory allocation with initialization
p=10;
int main()
{
int *p, i,n;
cout<<”Enter size of the array”;
cin>>n;
p=new int[n];
cout<<”\n enter array elements”;
for(i=0;i<n;i++)
cin>>*(p+i);
delete p;
}
In the above program, the class consist of one member variable, a constructor to initialize and
a function to display the member variable. In main function the statement
Test *p = new Test(10);
Can be rewritten as
Test *p;
p= new Test(10);
Does three operations viz.
• Creating a pointer of class type
• Allocating memory for an object from heap area
• Calling appropriate constructor
1200
The memory allocated on the heap area(1200 in the above figure) will be released when the
following statement is executed.
delete p;
• We can also create an array of dynamic objects using the following code.
int main()
{
Test *p = {new Test(10), new Test(20)};
for(int i=0;i<2;i++)
p[i]->disp();
delete [ ] p;
}
a a
10 10
1200 1100
P[0] p[1]
1200 1100
#include <iostream>
using namespace std;
class ABC
{
private:
int x,y;
public:
ABC () //constructor 1 with no arguments
{
x = y = 0;
}
ABC(int a) //constructor 2 with one argument
{
x = y = a;
}
ABC(int a,int b) //constructor 3 with two argument
{
x = a;
y = b;
}
void display()
{
cout << "x = " << x << " and " << "y = " << y << endl;
}
};
int main()
{
ABC cc1; //constructor 1
ABC cc2(10); //constructor 2
ABC cc3(10,20); //constructor 3
[Link]();
[Link]();
[Link]();
return 0;
} //end of program