C++ Object and Class
C++ Object and Class
C++ Object
In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.
In other words, object is an entity that has state and behavior. Here, state means data
and behavior means functionality.
Object is an instance of a class. All the members of the class can be accessed through
object.
Let's see an example to create object of student class using s1 as the reference variable.
C++ Class
In C++, class is a group of similar objects. It is a template from which objects are
created. It can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. }
C++ Object and Class Example
Let's see an example of class that has two fields: id and name. It creates instance of the
class, initializes the object and prints the object value.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. };
8. int main() {
9. Student s1; //creating an object of Student
10. s1.id = 201;
11. s1.name = "Sonoo Jaiswal";
12. cout<<s1.id<<endl;
13. cout<<s1.name<<endl;
14. return 0;
15. }
The variables which are declared in any class by using any fundamental data types (like
int, char, float etc) or derived data type (like class, structure, pointer etc.) are known
as Data Members. And the functions which are declared either in private section of
public section are known as Member functions.
1. Private members
2. Public members
1) Private members
The members which are declared in private section of the class (using private access
modifier) are known as private members. Private members can also be accessible within
the same class in which they are declared.
2) Public members
The members which are declared in public section of the class (using public access
modifier) are known as public members. Public members can access within the class and
outside of the class by using the object name of the class in which they are declared.
class Test
{
private:
int a;
float b;
void getA()
{ a=10; }
public:
int count;
void getB() { b=20; }
};
Here, a, b, and name are the private data members and count is a public data member.
While, getA() is a private member function and getB() is public member functions.
C++ program that will demonstrate, how to declare, define and access data
members an member functions in a class?
#include <iostream>
#include <string.h>
using namespace std;
#define MAX_CHAR 30
//class definition
class person
{
//private data members
private:
int age;
age = a;
}
//main function
int main()
{
//creating an object of person class
person PER;
return 0;
}
Output
C++ Constructor
In C++, constructor is a special method which is invoked automatically at the time of
object creation. It is used to initialize the data members of object . The constructor in
C++ has the same name as class or structure.
o Default constructor
o Parameterized constructor
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }
Output:
#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of
Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}
Output:
C++ Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be
defined only once in a class. Like constructors, it is invoked automatically.
A destructor is defined like constructor. It must have same name as class. But it is
prefixed with a tilde sign (~).
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
12. cout<<"Destructor Invoked"<<endl;
13. }
14. };
15. int main(void)
16. {
17. Employee e1; //creating an object of Employee
18. Employee e2; //creating an object of Employee
19. return 0;
20. }
In C++, we can make operators to work for user defined classes. This means
C++ has the ability to provide the operators with a special meaning for a data
type, this ability is known as operator overloading.
For example, we can overload an operator ‘+’ in a class like String so that we
can concatenate two strings by just using +.
Other example classes where arithmetic operators may be overloaded are
Complex Number, Fractional Number, Big Integer, etc.
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2; // An example call to "operator+"
c3.print();
}
What is the difference between operator functions and normal functions?
Operator functions are same as normal functions. The only differences are,
name of an operator function is always operator keyword followed by symbol of
operator and operator functions are called when the corresponding operator is
used.
Following is an example of global operator function.
#include<iostream>
class Complex {
private:
public:
void print() { cout << real << " + i" << imag << endl; }
};
{
return Complex(c1.real + c2.real, c1.imag + c2.imag);
int main()
c3.print();
return 0;
Inheritance in c++ is a mechanism in which one object acquires all the properties
and behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).
The idea behind inheritance in c++ is that you can create new classes that are built
upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the
parent class.
Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};
// Single inheritance
#include <iostream>
class Vehicle {
public:
Vehicle()
};
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
Multiple Inheritance: Multiple Inheritance is a feature of C++ where a class
can inherit from more than one classes. i.e one sub class is inherited from
more than one base classes.
// multiple inheritance
#include <iostream>
class Vehicle {
public:
Vehicle()
}
};
class FourWheeler {
public:
FourWheeler()
};
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
This is a 4 wheeler Vehicle
// Multilevel Inheritance
#include <iostream>
// base class
class Vehicle
public:
Vehicle()
};
{ public:
fourWheeler()
};
public:
Car()
{
cout<<"Car has 4 Wheels"<<endl;
};
// main function
int main()
Car obj;
return 0;
Output
This is a Vehicle
Objects with 4 wheels are vehicles
Car has 4 Wheels
Hierarchical Inheritance: In this type of inheritance, more than one sub class
is inherited from a single base class. i.e. more than one derived class is created
from a single base class.
// C++ program to implement
// Hierarchical Inheritance
#include <iostream>
// base class
class Vehicle
public:
Vehicle()
};
// first sub class
};
};
// main function
int main()
Car obj1;
Bus obj2;
return 0;
Output
This is a Vehicle
This is a Vehicle
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by
combining more than one type of inheritance. For example: Combining
Hierarchical inheritance and Multiple Inheritance.
Below image shows the combination of hierarchical and multiple inheritance:
#include <iostream>
// base class
class Vehicle
{
public:
Vehicle()
};
//base class
class Fare
public:
Fare()
cout<<"Fare of Vehicle\n";
};
{
};
};
// main function
int main()
Bus obj2;
return 0;
Output
This is a Vehicle
Fare of Vehicle
Modes of Inheritance
1. Public mode: If we derive a sub class from a public base class. Then the
public member of the base class will become public in the derived class and
protected members of the base class will become protected in derived class.
2. Protected mode: If we derive a sub class from a Protected base class. Then
both public member and protected members of the base class will become
protected in derived class.
3. Private mode: If we derive a sub class from a Private base class. Then both
public member and protected members of the base class will become
Private in derived class.
1. #include <iostream>
2. using namespace std;
3. class Animal {
4. public:
5. void eat(){
6. cout<<"Eating...";
7. }
8. };
9. class Dog: public Animal
10. {
11. public:
12. void eat()
13. {
14. cout<<"Eating bread...";
15. }
16. };
17. int main(void) {
18. Dog d = Dog();
19. d.eat();
20. return 0;
21. }
Output:
Eating bread...
The virtual base class is used when a derived class has multiple copies of the base class.
Example Code
#include <iostream>
using namespace std;
class B {
public: int b;
};
class D1 : public B {
public: int d1;
};
class D2 : public B {
public: int d2;
};
int main() {
D3 obj;
Example Code
#include<iostream>
using namespace std;
class B {
public: int b;
};
int main() {
D3 obj;
obj.d1 = 60;
obj.d2 = 70;
obj.d3 = 80;
Output
B : 30
D1 : 60
D2 : 70
D3 : 80
\
void geeks()
{
int var = 20;
// Driver program
int main()
{
geeks();
}
Pointers and objects : C++ allows you to have pointers to objects. The pointers
pointing to objects are referred to as Object Pointers.
Just like other pointers, the object pointers are declared by placing in front of a
object pointer's name. It takes the following general form :
class-name ∗ object-pointer ;
where class-name is the name of an already defined class and object-pointer is the
pointer to an object of this class type. For example, to declare optr as an object
pointer of Sample class type, we shall write
Sample ∗optr ;
where Sample is already defined class. When accessing members of a class using
an object pointer, the arrow operator (->) is used instead of dot operator.
The following program illustrates how to access an object given a pointer to it.
This C++ program illustrates the use of object pointer
#include<iostream.h>
#include<conio.h>
class Time
{
short int hh, mm, ss;
public:
Time()
{
hh = mm = ss = 0;
}
void getdata(int i, int j, int k)
{
hh = i;
mm = j;
ss = k;
}
void prndata(void)
{
cout<<"\nTime is "<<hh<<":"<<mm<<":"<<ss<<"\n";
}
};
void main()
{
clrscr();
Time T1, *tptr;
T1.getdata(12,22,11);
T1.prndata();
tptr = &T1;
cout<<"Printing members using the object pointer ";
tptr->prndata();
getch();
}
Every object in C++ has access to its own address through an important pointer
called this pointer. The this pointer is an implicit parameter to all member
functions. Therefore, inside a member function, this may be used to refer to the
invoking object.
Friend functions do not have a this pointer, because friends are not members of a
class. Only member functions have a this pointer.
#include <iostream>
class Box {
public:
// Constructor definition
Box(double l = 2.0, double b = 2.0, double h = 2.0) {
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
}
double Volume() {
return length * breadth * height;
}
int compare(Box box) {
return this->Volume() > box.Volume();
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
int main(void) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
Box Box2(8.5, 6.0, 2.0); // Declare box2
if(Box1.compare(Box2)) {
cout << "Box2 is smaller than Box1" <<endl;
} else {
cout << "Box2 is equal to or larger than Box1" <<endl;
}
C++ polymorphism means that a call to a member function will cause a different
function to be executed depending on the type of object that invokes the function.
Consider the following example where a base class has been derived by other two
classes −
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape( int a = 0, int b = 0){
width = a;
height = b;
}
int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape {
public:
Rectangle( int a = 0, int b = 0):Shape(a, b) { }
int area () {
cout << "Rectangle class area :" <<endl;
return (width * height);
}
};
int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};
return 0;
}
When the above code is compiled and executed, it produces the following result −
V irtual Function
A virtual function is a function in a base class that is declared using the keyword
virtual. Defining in a base class a virtual function, with another version in a
derived class, signals to the compiler that we don't want static linkage for this
function.
What we do want is the selection of the function to be called at any given point in
the program to be based on the kind of object for which it is called. This sort of
operation is referred to as dynamic linkage, or late binding.
We can change the virtual function area() in the base class to the following −
class Shape {
protected:
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
};
The = 0 tells the compiler that the function has no body and above virtual function
will be called pure virtual function
return 0;
When the above code is compiled and executed, it produces the following result −
Constructor called.
Constructor called.
Box2 is equal to or larger than Box1