Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

Unit 2

Classes and Objects

 C++ Classes and Objects


Class: A class in C++ is the building block that leads to Object-Oriented programming. It is a
user-defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A C++ class is like a blueprint for an
object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brand but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits,
mileage are their properties.
 A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions
defines the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc
and member functions can be apply brakes, increase speed etc.
An Object is an instance of a Class. When a class is defined, no memory is allocated but when
it is instantiated (i.e. an object is created) memory is allocated.
A class is defined in C++ using keyword class followed by the name of class. The body of
class is defined inside the curly brackets and terminated by a semicolon at the end.

Declaring Objects: When a class is defined, only the specification for the object is defined; no
memory or storage is allocated. To use the data and access functions defined in the class, you
need to create objects.

Syntax:
ClassName ObjectName;
Accessing data members and member functions: The data members and member functions
of class can be accessed using the dot(‘.’) operator with the object. For example if the name of
object is obj and you want to access the member function with the name printName() then you
will have to write obj.printName() .

Member Functions in Classes


There are 2 ways to define a member function:
 Inside class definition
 Outside class definition
Example 1: Object and Class in C++ Programming

// Program to illustrate the working of


// objects and class in C++ Programming

#include <iostream>

// create a class
class Room {

public:
double length;
double breadth;
double height;

double calculateArea() {
return length * breadth;
}

double calculateVolume() {
return length * breadth * height;
}
};

int main() {

// create object of Room class


Room room1;

// assign values to data members


room1.length = 42.5;
room1.breadth = 30.8;
room1.height = 19.2;

// calculate and display the area and volume of the room


cout << "Area of Room = " << room1.calculateArea() << endl;
cout << "Volume of Room = " << room1.calculateVolume() << endl;

return 0;
}

Output
Area of Room = 1309
Volume of Room = 25132.8

 Access specifier

The public keyword is an access specifier. Access specifiers define how the


members (attributes and methods) of a class can be accessed. In the
example above, the members are public - which means that they can be
accessed and modified from outside the code.

However, what if we want members to be private and hidden from the


outside world?

In C++, there are three access specifiers:

 public - members are accessible from outside the class


 private - members cannot be accessed (or viewed) from outside the
class
 protected - members cannot be accessed from outside the class,
however, they can be accessed in inherited classes. You will learn more
about Inheritance later.

In the following example, we demonstrate the differences


between public and private members:

Example
class MyClass {
  public:    // Public access specifier
    int x;   // Public attribute
  private:   // Private access specifier
    int y;   // Private attribute
};

int main() {
  MyClass myObj;
  myObj.x = 25;  // Allowed (public)
  myObj.y = 50;  // Not allowed (private)
  return 0;
}

Output:

error: y is private

 Member function 
A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of the
class of which it is a member, and has access to all the members of a class for that
object.
Member functions can be defined within the class definition or separately
using scope resolution operator,: −. Defining a member function within the class
definition declares the function inline, even if you do not use the inline specifier. So
either you can define Volume() function as below −

#include <iostream>

using namespace std;

class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

// Member functions declaration


double getVolume(void);
void setLength( double len );
void setBreadth( double bre );
void setHeight( double hei );
};

// Member functions definitions


double Box::getVolume(void) {
return length * breadth * height;
}

void Box::setLength( double len ) {


length = len;
}
void Box::setBreadth( double bre ) {
breadth = bre;
}
void Box::setHeight( double hei ) {
height = hei;
}

// Main function for the program


int main() {
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here

// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);

// volume of box 1
volume = Box1.getVolume();
cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2
volume = Box2.getVolume();
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}

When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560

Static Members of a C++ Class


We can define class members static using static keyword. When we declare a
member of a class as static it means no matter how many objects of the class are
created, there is only one copy of the static member.
A static member is shared by all objects of the class. All static data is initialized to
zero when the first object is created, if no other initialization is present. We

Static Function Members


By declaring a function member as static, you make it independent of any particular
object of the class. A static member function can be called even if no objects of the
class exist and the static functions are accessed using only the class name and the
scope resolution operator ::.
A static member function can only access static data member, other static member
functions and any other functions from outside the class.
Static member functions have a class scope and they do not have access to
the this pointer of the class. You could use a static member function to determine
whether some objects of the class have been created or not.
Friend class and Friend function in C++
Friend Class A friend class can access private and protected members of
other class in which it is declared as friend. It is sometimes useful to allow a
particular class to access private members of other class. For example, a
LinkedList class may be allowed to access private members of Node. 

class Node {

private:

    int key;

    Node* next;

    /* Other members of Node Class */

    // Now class  LinkedList can

    // access private members of Node

    friend class LinkedList;

};

Friend Function Like friend class, a friend function can be given a special


grant to access private and protected members. A friend function can be: 
a) A member of another class 
b) A global function 

What is a friend function?


A friend function is a function that is specified outside a class but has the
ability to access the class members’ protected and private data. A friend
can be a member’s function, function template, or function, or a class or
class template, in which case the entire class and all of its members are
friends.

Why do we need friend functions?


In special cases when a class’s private data needs to be accessed directly
without using objects of that class, we need friend functions. For instance,
let’s consider two classes: Director and Doctor. We may want the
function gross_salary to operate the objects of both these classes. The
function does not need to be a member of either of the classes.
// Program to illustrate friend function

#include<iostream>

using namespace std;

class integer
{
Static int a, b;
public:
void set_value()
{
a=50;
b=30;
}
friend int mean(integer s); //declaration of friend
function
};

int mean(integer s)
{
return int(s.a+s.b)/2.0; //friend function definition
}

int main()
{
integer c;
c.set_value();
cout<< "Mean value:" <<mean(c);
return 0;
}

The output of our program will be: Mean value: 40


Array of Objects in c++
 Like array of other user-defined data types, an array of type class can also be created.
 The array of type class contains the objects of the class as its individual elements.
 Thus, an array of a class type is also known as an array of objects.
 An array of objects is declared in the same way as an array of any built-in data type.

Syntax:

class_name array_name [size];

include <iostream>    

class MyClass

{   

int x; 

public:   

void setX(int i)

x = i;

int getX()

return x; } 

};   

void main() 

  MyClass obs[4]; 

  int i; 

    for(i=0; i < 4; i++)   


  obs[i].setX(i);   

  for(i=0; i < 4; i++)   

  cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";     

getch(); 

Objects as Function Arguments in c++


 Similar to passing primary data-type variables, we can also pass object as argument to
the function. Objects can be passed by two methods:

1. Call by value: In this method a copy of entire object is created to pass into another
function. When we make changes in the object inside calling function then only local copy of the
object will be affected, there is no change in called function. Both copies of the object will be
identical.
2. Call by reference: In this method no separate copy of the object is created, instead we
are passing address (&) of object to the function. When an object is modified inside the calling
function then the actual object is also affected in the called function. Call by reference method
can be used by passing argument via reference variable or pointer.

Constructors in C++
What is constructor? 
A constructor is a special type of member function of a class which initializes
objects of a class. In C++, Constructor is automatically called when
object(instance of class) create. It is special member function of the class
because it does not have any return type.

class Wall {
public:
// create a constructor
Wall() {
// code
}
};

 Constructor has same name as the class itself


 Constructors don’t have return type
 A constructor is automatically called when an object is created.
 It must be placed in public section of class.
 If we do not specify a constructor, C++ compiler generates a default
constructor for object (expects no parameters and has an empty body).
 

Types of Constructors
1. Default Constructors:  Default constructor is the constructor which
doesn’t take any argument. It has no parameters.
 CPP
// concept of Constructors
#include <iostream>
using namespace std;
 
class construct
{
public:
    int a, b;
 
    construct()     // Default Constructor
    {
        a = 10;
        b = 20;
    }
};
 
int main()
{
    // Default constructor called automatically
    // when the object is created
    construct c;
    cout << "a: " << c.a << endl
         << "b: " << c.b;
    return 1;
}

Output: 
a: 10
b: 20

Note: Even if we do not define any constructor explicitly, the compiler will


automatically provide a default constructor implicitly.

2. Parameterized Constructors: It is possible to pass arguments to


constructors. Typically, these arguments help initialize an object when it is
created. To create a parameterized constructor, simply add parameters to it
the way you would to any other function. When you define the constructor’s
body, use the parameters to initialize the object. 
 CPP
// CPP program to illustrate
// parameterized constructors
#include <iostream>
using namespace std;
 
class Point
{
private:
    int x, y;
 
public:
    // Parameterized Constructor
    Point(int x1, int y1)
    {
        x = x1;
        y =; y1
    }
 
    int getX()
    {
        return x;
    }
    int getY()
    {
        return y;
    }
};
 
int main()
{
    // Constructor called
    Point p1(10, 15);
 
    // Access values assigned by constructor
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
 
    return 0;
}

Output: 
p1.x = 10, p1.y = 15
When an object is declared in a parameterized constructor, the initial values
have to be passed as arguments to the constructor function. The normal way
of object declaration may not work. The constructors can be called explicitly
or implicitly.
Example e = Example(0, 50); // Explicit call

Example e(0, 50); // Implicit call


 Uses of Parameterized constructor: 
1. It is used to initialize the various data elements of different
objects with different values when they are created.
2. It is used to overload constructors.

3. Copy Constructor: A copy constructor is a member function which


initializes an object using another object of the same class. Detailed article
on Copy Constructor.
Whenever we define one or more non-default constructors( with parameters )
for a class, a default constructor( without parameters ) should also be
explicitly defined as the compiler will not provide a default constructor in this
case. However, it is not necessary but it’s considered to be the best practice
to always define a default constructor. 

 CPP
// Illustration
#include "iostream"
using namespace std;
 
class point
{
private:
  double x, y;
 
public:
   
  // Non-default Constructor &
  // default Constructor
  point (double px, double py)
  {
    x = px, y = py;
  }
};
 
int main(void)
{
 
  // Define an array of size
  // 10 & of type point
  // This line will cause error
  point a[10];
 
  // Remove above line and program
  // will compile without error
  point b = point(5, 6);
}

Output: 
Error: point (double px, double py): expects 2 arguments, 0
provided

\\copy contructor ex 2
#include<iostream>
using namespace std;
 class Point
{
private:
    int x, y;
public:
    Point(int x1, int y1) { x = x1; y = y1; }
 
    // Copy constructor
    Point(const Point &p1) {x = p1.x; y = p1.y; }
     int getX()            {  return x; }
    int getY()            {  return y; }
};
 int main()
{    Point p1(10, 15); // Normal constructor is called here
    Point p2 = p1; // Copy constructor is called here
     // Let us access values assigned by constructors
    cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
    cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
     return 0;
}

Output: 
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
 
Multiple constructor: Multiple constructors is a category of constructor in which a
class can have more than one constructor. This is also known as constructor overloading. All
constructors are defined with the same name as the class name they belong to. Each of the
constructors contains different number of arguments. Depending upon the number of arguments
and their data type, the compiler executes appropriate constructor.

Example:-

#include<iostream.h>

#include<conio.h>

class integer

int m, n;
public:
integer()
{

m = 0;
n = 0;
}// constructor 1

integer(int a, int b)

{
m = a;
n = b;
cout<<"value of m="<<a;
cout<<"value of n="<<b;
} // constructor 2

};
void main()

{
clrscr();
integer i1;
integer i2(20,40);
getch();

In the above example, two constructors are defined and invoked; this is referred as multiple
constructors.
The first constructor does not accept any argument and the second accepts two integer arguments.
In void main( ):
integer i1; - This statement invokes first constructor.
integer i2 (20, 40); -This statement invokes second constructor. 

Constructors and Destructors in C++


Constructors are special class functions which performs initialization of every object. The
Compiler calls the Constructor whenever an object is created. Constructors initialize values to
object members after storage is allocated to the object.

Whereas, Destructor on the other hand is used to destroy the class object.

Before moving forward with Constructors and Destructors in C++ language, check these
topics out to understand the concept better:

 Function in C++
 Class and Objects in C++
 Data Members

Let's start with Constructors first, following is the syntax of defining a constructor function in
a class:

class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};
Copy
While defining a contructor you must remeber that the name of constructor will be same as
the name of the class, and contructors will never have a return type.
Constructors can be defined either inside the class definition or outside class definition using
class name and scope resolution :: operator.
class A
{
public:
int i;
A(); // constructor declared
};

// constructor definition
A::A()
{
i = 1;
}
Copy
Types of Constructors in C++
Constructors are of three types:
1. Default Constructor
2. Parametrized Constructor
3. Copy COnstructor

Default Constructors
Default constructor is the constructor which doesn't take any argument. It has no parameter.
Syntax:
class_name(parameter1, parameter2, ...)
{
// constructor Definition
}
Copy
For example:
class Cube
{
public:
int side;
Cube()
{
side = 10;
}
};

int main()
{
Cube c;
cout << c.side;
}
Copy

10
In this case, as soon as the object is created the constructor is called which initializes its data
members.
A default constructor is so important for initialization of object members, that even if we do
not define a constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
public:
int side;
};

int main()
{
Cube c;
cout << c.side;
}
Copy
0 or any random value
In this case, default constructor provided by the compiler will be called which will initialize
the object data members to default value, that will be 0 or any random integer value in this
case.

Parameterized Constructors
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
For example:
class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};

int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
Copy

10
20
30
By using parameterized construcor in above case, we have initialized 3 objects with user
defined values. We can have any number of parameters in a constructor.

Copy Constructors
These are special type of Constructors which takes an object as argument, and is used to copy
values of data members of one object into other object. We will study copy constructors in
detail later.

Constructor Overloading in C++


Just like other member functions, constructors can also be overloaded. Infact when you have
both default and parameterized constructors defined in your class you are having Overloaded
Constructors, one with no parameter and other with parameter.
You can have any number of Constructors in a class that differ in parameter list.
class Student
{
public:
int rollno;
string name;
// first constructor
Student(int x)
{
rollno = x;
name = "None";
}
// second constructor
Student(int x, string str)
{
rollno = x;
name = str;
}
};

int main()
{
// student A initialized with roll no 10 and name None
Student A(10);

// student B initialized with roll no 11 and name John


Student B(11, "John");
}
Copy
In above case we have defined two constructors with different parameters, hence overloading
the constructors.
One more important thing, if you define any constructor explicitly, then the compiler will not
provide default constructor and you will have to define it yourself.
In the above case if we write Student S; in main(), it will lead to a compile time error, because
we haven't defined default constructor, and compiler will not provide its default constructor
because we have defined other parameterized constructors.

Destructors in C++
Destructor is a special class function which destroys the object as soon as the scope of object
ends. The destructor is called automatically by the compiler when the object goes out of
scope.
The syntax for destructor is same as that for the constructor, the class name is used for the
name of destructor, with a tilde ~ sign as prefix to it.
class A
{
public:
// defining destructor for class
~A()
{
// statement
}
};
Copy
Destructors will never have any arguments.
Example to see how Constructor and Destructor are called
Below we have a simple class A with a constructor and destructor. We will create object of
the class and see when a constructor is called and when a destructor gets called.
class A
{
// constructor
A()
{
cout << "Constructor called";
}

// destructor
~A()
{
cout << "Destructor called";
}
};

int main()
{
A obj1; // Constructor Called
int x = 1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Copy

Constructor called
Constructor called
Destructor called
Destructor called
When an object is created the constructor of that class is called. The object reference is
destroyed when its scope ends, which is generally after the closing curly bracket } for the
code block in which it is created.
The object obj2 is destroyed when the if block ends because it was created inside the if block.
And the object obj1 is destroyed when the main() function ends.

Single Definition for both Default and Parameterized Constructor


In this example we will use default argument to have a single definition for both defualt and
parameterized constructor.
class Dual
{
public:
int a;
Dual(int x=0)
{
a = x;
}
};
int main()
{
Dual obj1;
Dual obj2(10);
}
Multiple constructor
The technique of having two (or more) constructors in a class is known as
constructor overloading. A class can have multiple constructors that differ in the
number and/or type of their parameters. It's not, however, possible to have two
constructors with the exact same parameters.
Multiple constructor: Multiple constructors is a category of constructor in which a
class can have more than one constructor. This is also known as constructor
overloading. All constructors are defined with the same name as the class name
they belong to. Each of the constructors contains different number of arguments.
Depending upon the number of arguments and their data type, the compiler
executes appropriate constructor.

Example:-

#include<iostream.h>

#include<conio.h>

class integer

int m, n;

public:

integer()

m = 0;

n = 0;

}// constructor 1

integer(int a, int b)

{
m = a;

n = b;

cout<<"value of m="<<a;

cout<<"value of n="<<b;

} // constructor 2

};

void main()

clrscr();

integer i1;

integer i2(20,40);

getch();

In the above example, two constructors are defined and invoked; this is referred as
multiple constructors.

The first constructor does not accept any argument and the second accepts two
integer arguments.

In void main( ):

integer i1; - This statement invokes first constructor.

integer i2 (20, 40); -This statement invokes second constructor. 

constructor with default arguments in c++

A default constructor is a constructor that either has no parameters, or if it has parameters,


all the parameters have default values. If no user-defined constructor exists for a class A and
one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

You might also like