0% found this document useful (0 votes)
37 views35 pages

C++ Object and Class

Uploaded by

Vrishhti Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
37 views35 pages

C++ Object and Class

Uploaded by

Vrishhti Goel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

C++ Object and Class

Since C++ is an object-oriented language, program is designed using objects and


classes in C++.

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 a runtime entity, it is created at runtime.

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.

1. Student s1; //creating an object of Student

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. }

Data Members and Member Functions in C++


programming
"Data Member" and "Member Functions" are the new names/terms for the members
of a class, which are introduced in C++ programming language.

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.

There are two types of data members/member functions in C++:

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.

Consider the example:

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;

//public member functions


public:
//function to get name and age
void get( int a)
{

age = a;
}

//function to print name and age


void put()
{

cout<< "Age: " <<age <<endl;


}
};

//main function
int main()
{
//creating an object of person class
person PER;

//calling member functions


PER.get( 23);
PER.put();

return 0;
}

Output

Name: Manju Tomar


Age: 23

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.

There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

C++ Default Constructor


A constructor which has no argument is known as default constructor. It is invoked at
the time of creating object.

Let's see the simple example of C++ default 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:

Default Constructor Invoked


Default Constructor Invoked

C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It is used to
provide different values to distinct objects.

Let's see the simple example of C++ Parameterized Constructor.

#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:

101 Sonoo 890000


102 Nakul 59000

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 (~).

C++ Constructor and Destructor Example


Let's see an example of constructor and destructor in C++ which is called automatically.

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;}

// This is automatically called when '+' is used with


// between two Complex objects
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};

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>

using namespace std;

class Complex {

private:

int real, imag;

public:

Complex(int r = 0, int i =0) {real = r; imag = i;}

void print() { cout << real << " + i" << imag << endl; }

// The global operator function is made friend of this class so

// that it can access private members

friend Complex operator + (Complex const &, Complex const &);

};

Complex operator + (Complex const &c1, Complex const &c2)

{
return Complex(c1.real + c2.real, c1.imag + c2.imag);

int main()

Complex c1(10, 5), c2(2, 4);

Complex c3 = c1 + c2; // An example call to "operator+"

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.

Why use inheritance in c++

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance

o Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class.

The syntax of c++ Inheritance


class subclass_name : access_mode base_class_name
{
//body of subclass
};
Types of Inheritance in C++
1. Single Inheritance: In single inheritance, a class is allowed to inherit from
only one class. i.e. one sub class is inherited by one base class only.

Syntax:
class subclass_name : access_mode base_class
{
//body of subclass
};

/ C++ program to explain

// Single inheritance

#include <iostream>

using namespace std;


// base class

class Vehicle {

public:

Vehicle()

cout << "This is a Vehicle" << endl;

};

// sub class derived from a single base classes

class Car: public Vehicle{

};

// main function

int main()

// creating object of sub class will

// invoke the constructor of base classes

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.

class subclass_name : access_mode base_class1, access_mode


base_class2, ....
{
//body of subclass
};

// C++ program to explain

// multiple inheritance

#include <iostream>

using namespace std;

// first base class

class Vehicle {

public:

Vehicle()

cout << "This is a Vehicle" << endl;

}
};

// second base class

class FourWheeler {

public:

FourWheeler()

cout << "This is a 4 wheeler Vehicle" << endl;

};

// sub class derived from two base classes

class Car: public Vehicle, public FourWheeler {

};

// main function

int main()

// creating object of sub class will

// invoke the constructor of base classes

Car obj;
return 0;

Output
This is a Vehicle
This is a 4 wheeler Vehicle

3. Multilevel Inheritance: In this type of inheritance, a derived class is created


from another derived class.

// C++ program to implement

// Multilevel Inheritance

#include <iostream>

using namespace std;

// base class
class Vehicle

public:

Vehicle()

cout << "This is a Vehicle" << endl;

};

// first sub_class derived from class vehicle

class fourWheeler: public Vehicle

{ public:

fourWheeler()

cout<<"Objects with 4 wheels are vehicles"<<endl;

};

// sub class derived from the derived base class fourWheeler

class Car: public fourWheeler{

public:

Car()

{
cout<<"Car has 4 Wheels"<<endl;

};

// main function

int main()

//creating object of sub class will

//invoke the constructor of base classes

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>

using namespace std;

// base class

class Vehicle

public:

Vehicle()

cout << "This is a Vehicle" << endl;

};
// first sub class

class Car: public Vehicle

};

// second sub class

class Bus: public Vehicle

};

// main function

int main()

// creating object of sub class will

// invoke the constructor of base class

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:

// C++ program for Hybrid Inheritance

#include <iostream>

using namespace std;

// base class

class Vehicle
{

public:

Vehicle()

cout << "This is a Vehicle" << endl;

};

//base class

class Fare

public:

Fare()

cout<<"Fare of Vehicle\n";

};

// first sub class

class Car: public Vehicle

{
};

// second sub class

class Bus: public Vehicle, public Fare

};

// main function

int main()

// creating object of sub class will

// invoke the constructor of base class

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.

C++ Function Overriding


If derived class defines same function as defined in its base class, it is known as function
overriding in C++.

It is used to achieve runtime polymorphism. It enables you to provide specific


implementation of the function which is already provided by its base class.

C++ Function Overriding Example


Let's see a simple example of Function overriding in C++. In this example, we are
overriding the eat() function.

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;
};

class D3 : public D1, public D2 {


public: int d3;
};

int main() {
D3 obj;

obj.b = 40; //Statement 1, error will occur


obj.b = 30; //statement 2, error will occur
obj.d1 = 60;
obj.d2 = 70;
obj.d3 = 80;

cout<< "\n B : "<< obj.b


cout<< "\n D1 : "<< obj.d1;
cout<< "\n D2: "<< obj.d2;
cout<< "\n D3: "<< obj.d3;
}

Example Code
#include<iostream>
using namespace std;
class B {
public: int b;
};

class D1 : virtual public B {


public: int d1;
};

class D2 : virtual public B {


public: int d2;
};

class D3 : public D1, public D2 {


public: int d3;
};

int main() {
D3 obj;

obj.b = 40; // statement 3


obj.b = 30; // statement 4

obj.d1 = 60;
obj.d2 = 70;
obj.d3 = 80;

cout<< "\n B : "<< obj.b;


cout<< "\n D1 : "<< obj.d1;
cout<< "\n D2 : "<< obj.d2;
cout<< "\n D3 : "<< obj.d3;
}

Output
B : 30
D1 : 60
D2 : 70
D3 : 80
\

Pointers are symbolic representation of addresses. They enable programs to


simulate call-by-reference as well as to create and manipulate dynamic data
structures. It’s general declaration in C/C++ has the format:
Syntax:
datatype *var_name;
int *ptr; //ptr can point to an address which holds int data
How to use a pointer?

 Define a pointer variable


 Assigning the address of a variable to a pointer using unary operator (&)
which returns the address of that variable.
 Accessing the value stored in the address using unary operator (*) which
returns the value of the variable located at the address specified by its
operand.

// C++ program to illustrate Pointers in C++


#include <stdio.h>

void geeks()
{
int var = 20;

// declare pointer variable


int *ptr;

// note that data type of ptr and var must be same


ptr = &var;

// assign the address of a variable to a pointer


printf("Value at ptr = %p \n",ptr);
printf("Value at var = %d \n",var);
printf("Value at *ptr = %d \n", *ptr);
}

// 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.

C++ Declaration and Use of 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

/* C++ Pointers and Objects. Declaration and Use


* of Pointers. This program demonstrates the
* use of pointers in C++ */

#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>

using namespace std;

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;
}

The word polymorphism means having many forms. Typically, polymorphism


occurs when there is a hierarchy of classes and they are related by inheritance.

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);
}
};

class Triangle: public Shape {


public:
Triangle( int a = 0, int b = 0):Shape(a, b) { }

int area () {
cout << "Triangle class area :" <<endl;
return (width * height / 2);
}
};

// Main function for the program


int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);

// store the address of Rectangle


shape = &rec;

// call rectangle area.


shape->area();

// store the address of Triangle


shape = &tri;

// call triangle area.


shape->area();

return 0;
}

When the above code is compiled and executed, it produces the following result −

Parent class area :


Parent class area :

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.

Pure Virtual Functions


It is possible that you want to include a virtual function in a base class so that it
may be redefined in a derived class to suit the objects of that class, but that there is
no meaningful definition you could give for the function in the base class.

We can change the virtual function area() in the base class to the following −

class Shape {

protected:

int width, height;

public:

Shape(int a = 0, int b = 0) {

width = a;

height = b;

// pure virtual function

virtual int area() = 0;

};

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

You might also like