Concept of object and class in C++

 A class is a way to bind the data and its associated functions together. 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 class is like a blueprint for an object.

An Object is an instance of a Class. When a class is defined, objects can be created by placing their names immediately after closing the brace.

Generally a class specification has two parts:

  • class declaration 
  • class function definition

A class is declared as:

class class_name

{

private:

variable declarations;

function declarations;

public:

variable declarations;

function declarations;

};

Defining Class and Declaring Objects

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.

defining class:

class className
   {
   // some data
   // some functions
   };

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. The class specification provides only the template and does not create any memory space for the objects.

Access specifiers(visibility specifiers/labels):

  1. Private
  2. Protected
  3. Public 

         Private and public:

                  The keywords private and public are called as the visibility labels. The data hiding is achieved by the keyword private and is the key feature of C++.The data and the functions under the private sections of a class are accessible only within the class but not from the outside of the class.  The data and the functions under the public section are accessed from outside of a class. If there is no visibility label specified in a class then by default the data and functions are under the private section.If the member function has smaller body part we can define it inside the class but if body part is larger then it must be defined outside the class.

    Definition of function outside of the class:

syntax:

class class_name

{

Access specifier_type:

data members;

function members;

void input()

{

//defined here;

}

void display();

};

return_type class_name::function_name()// definition of the function

{

// statements

}

Any function that is declared inside the class is defined outside the class using scope resolution operator which identifies the return type and the class name under which the particular function is declared.

An example:

#include<iostream>
#include<conio.h>
using namespace std;
class student
{
private:

char name[20];
int roll;
public: void inputdata()
{
cout<<“enter name and roll”;
cin>>name>>roll;
}
void display();
};
void student::display()
{
cout<<“name=”<<name<<“\t”<<“roll=”<<roll;
}
main()
{
student s1;
s1.inputdata();
s1.display();

}

output:

enter name and roll XYZ

20

name=XYZ roll=20

 Object as an argument:

              We can pass objects of a class as a function arguments in two ways:

  1. (Passing object by value): A copy of entire object is passed to the function.
  2. (Passing object by reference): Only address of the object is passed to the function.

The first method is called passing objects by value because the copy of the object is passed to the function and any changes made to the object inside the called function do not affect the object used to call the function.

 The second method is called pass by reference in which address of the object is passed to the function, the called function directly works on the actual objects used to call the function. Any changes made to the objects inside the called function will reflect in the actual objects. Pass by reference method is more efficient because it requires only address of the object to be passed and not the entire object.

Example for object as an argument:

#include<iostream>
#include<conio.h>
using namespace std;
class time
{
int hour, minute, second;
public: void gettime(int h, int m, int s)
{
hour=h; minute=m; second=s;
}
void displaytime()
{
cout<<“hours=”<<hour<<“minutes=”<<minute<<“seconds=”<<second<<endl;

}
void sum(time,time);
};
void time::sum(time t1, time t2)
{
second=t1.second+t2.second;
minute=second/60;
second=second%60;
minute=minute+t1.minute+t2.minute;
hour=minute/60;
minute=minute%60;
hour=hour+t1.hour+t2.hour;
}
main()
{
time T1, T2, T3;
T1.gettime(9,10,15);
T2.gettime(10,12,20);
T3.sum(T1,T2);
cout<<“T1=”;T1.displaytime();
cout<<“T2=”;T2.displaytime();
cout<<“T3=”;T3.displaytime();
}

Output:

T1=hours=9minutes=10seconds=15

T2=hours=10minutes=12seconds=20

T3=hours=19minutes=22seconds=35

 

 An object can  also be passed as an argument to a non-member function. However such function can have access to the public member functions only through the objects passed to it as an arguments. These functions cannot have access to the private data members.

Member functions:

There are 2 ways to define a member function:

  • Inside class definition
  • Outside class definition

To define a member function outside the class definition we have to use the scope resolution :: operator along with class name and function name.

class Cube
{
    public:
    int side;
    int getVolume();
}

// member function defined outside class definition
int Cube :: getVolume()
{
    return side*side*side;
}

If we define the function inside the class we don’t need to declare it first we can directly define the function in the class.

class Cube
{
    public:
    int side;
    int getVolume()
    {
        return side*side*side;      //returns volume of cube
    }
};

Constructors:

Constructors are special member function whose task is to initialize the objects of its class. Constructors have the same name as the class and is invoked whenever an object of its associated class is created. It constructs the values of data members of the class so it is called constructor.
There are 3 types of constructors:

  • Default constructors
  • Parameterized constructors
  • Copy constructors

// C++ program to demonstrate constructors
#include <iostream>
#include<conio.h>
using namespace std;
class constructor
{
int a, b;
public:

//Default Constructor declared
constructor constructor();
constructor(int, int);// declaration of parameterized constructor
void display()
{
cout<<“a=”<<a<<endl;
cout<<“b=”<<b<<endl;
}
};
constructor::constructor() //default constructor definition
{
a=0;b=0;
}
constructor::constructor(int x, int y)//definition of parameterized constructor
{
a=x;b=y;
}
main()
{  
constructor c1, c2;
constructor c3(5,9), c4(10,25);
c1.display();
c2.display();
c3.display();
c4.display();
}

Output:

a=0

b=0

a=0

b=0

a=5

b=9

a=10

b=25

A Copy Constructor creates a new object, which is exact copy of the existing object. The compiler provides a default Copy Constructor to all the classes.

Syntax:

class-name (class-name &){}

Destructors:

Destructor is another special member function that is called by the compiler when the scope of the object ends.

// C++ program to explain destructors
  
#include <iostream>
#include<conio.h>
 
using namespace std;
class student
{
    public:
    int id;
      
    //Definition for Destructor
    ~student()
    {
        cout << “Destructor called for id: ” << id <<endl; 
    }
};
  
int main() 
  {
    student obj1;
    obj1.id=7;
    int i = 0;
    while ( i < 5 )
    {
        student obj2;
        obj2.id=i;
        i++;        
    } // Scope for obj2 ends here
  
    return 0;
  } // Scope for obj1 ends here

Output:

Destructor called for id: 0
Destructor called for id: 1
Destructor called for id: 2
Destructor called for id: 3
Destructor called for id: 4
Destructor called for id: 7

Leave a Reply

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert
%d bloggers like this: