0% found this document useful (0 votes)
49 views19 pages

Unit - 5

Uploaded by

Ajay Pathak
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)
49 views19 pages

Unit - 5

Uploaded by

Ajay Pathak
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/ 19

C++ Classes/Objects:

C++ is an object-oriented programming language.


Everything in C++ is associated with classes and objects, along with its attributes
and methods. For example: in real life, a car is an object. The car has attributes,
such as weight and color, and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the
class. These are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as
an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the class keyword:

Example

Create a class called "MyClass":

class MyClass { // The class

public: // Access specifier

int myNum; // Attribute (int variable)

string myString; // Attribute (string variable)

};

class MyClass { // The class

public: // Access specifier

int myNum; // Attribute (int variable)

string myString; // Attribute (string variable)

};
int main() {

MyClass myObj; // Create an object of MyClass

// Access attributes and set values

myObj.myNum = 15;

myObj.myString = "Some text";

// Print attribute values

cout << myObj.myNum << "\n";

cout << myObj.myString;

return 0;

Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance.
Inheritance is one of the most important feature of Object Oriented Programming.
Sub Class: The class that inherits properties from another class is called Sub class or Derived Class.
Super Class:The class whose properties are inherited by sub class is called Base Class or Super class.

Why and when to use inheritance?

Consider a group of vehicles. You need to create classes for Bus, Car and Truck. The methods
fuelAmount(), capacity(), applyBrakes() will be same for all of the three classes. If we create these classes
avoiding inheritance then we have to write all of these functions in each of the three classes as shown in
below figure:
You can clearly see that above process results in duplication of same code 3 times. This increases the
chances of error and data redundancy. To avoid this type of situation, inheritance is used. If we create a class
Vehicle and write these three functions in it and inherit the rest of the classes from the vehicle class, then we
can simply avoid the duplication of data and increase re-usability. Look at the below diagram in which the
three classes are inherited from vehicle class:

Using inheritance, we have to write the functions only one time instead of three times as we have inherited
rest of the three classes from base class(Vehicle).

Implementing inheritance in C++: For creating a sub-class which is inherited from the base class we have
to follow the below syntax.
Syntax:

class subclass_name : access_mode base_class_name

//body of subclass

};

using namespace std;

//Base class
class Parent
{
public:
int id_p;
};

// Sub class inheriting from Base Class(Parent)


class Child : public Parent
{
public:
int id_c;
};

//main function
int main()
{

Child obj1;

// An object of class child has all data members


// and member functions of class parent
obj1.id_c = 7;
obj1.id_p = 91;
cout << "Child id is " << obj1.id_c << endl;
cout << "Parent id is " << obj1.id_p << endl;

return 0;
}

Output:

Child id is 7
Parent id is 91

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.
Types of inheritance

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.

#include <iostream>
using namespace std;

// base class
class Vehicle {
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};

// sub class derived from two 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
2.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.

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

#include <iostream>
using namespace std;

// base class
class Vehicle
{
public:
Vehicle()
{
cout << "This is a Vehicle" << endl;
}
};
class fourWheeler: public Vehicle
{ public:
fourWheeler()
{
cout<<"Objects with 4 wheels are vehicles"<<endl;
}
};
// sub class derived from two base classes
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

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

Constructors in C++
What is constructor?
A constructor is a 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.
How constructors are different from a normal member function?
A constructor is different from normal functions in following ways:
• Constructor has same name as the class itself
• Constructors don’t have return type
• A constructor is automatically called when an object is created.
• If we do not specify a constructor, C++ compiler generates a default constructor for us (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.

#include <iostream>
using namespace std;

class construct
{
public:
int a, b;

// Default Constructor
construct()
{
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

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.

#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

3. Copy Constructor: A copy constructor is a member function which initializes an object using
another object of the same class.

#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 &p2) {x = p2.x; y = p2.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

Polymorphism in C++:
The word polymorphism means having many forms. In simple words, we can define polymorphism as the
ability of a message to be displayed in more than one form. A real-life example of polymorphism, a person
at the same time can have different characteristics.

In C++ polymorphism is mainly divided into two types:


• Compile time Polymorphism
• Runtime Polymorphism
Compile time polymorphism: This type of polymorphism is achieved by function overloading
or operator overloading.

Function Overloading: When there are multiple functions with same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by
change in number of arguments or/and change in type of arguments.
using namespace std;
class G
{
public:

// function with 1 int parameter


void func(int x)
{
cout << "value of x is " << x << endl;
}

// function with same name but 1 double parameter


void func(double x)
{
cout << "value of x is " << x << endl;
}

// function with same name and 2 int parameters


void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};

int main() {

G obj1;

// Which function is called will depend on the parameters passed


// The first 'func' is called
obj1.func(7);

// The second 'func' is called


obj1.func(9.132);

// The third 'func' is called


obj1.func(85,64);
return 0;
}
Output:

value of x is 7
value of x is 9.132
value of x and y is 85, 64

Operator Overloading: C++ also provide option to overload operators. For example, we can
make the operator (‘+’) for string class to concatenate two strings. We know that this is the
addition operator whose task is to add two operands. So a single operator ‘+’ when placed
between integer operands , adds them and when placed between string operands, concatenates
them.

#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();
}
Output:

12 + i9

Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.


• Function overriding on the other hand occurs when a derived class has a definition for
one of the member functions of the base class. That base function is said to
be overridden.

using namespace std;

class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }

void show ()
{ cout<< "show base class" <<endl; }
};

class derived:public base


{
public:
void print () //print () is already virtual function in derived class, we could also declared as
virtual void print () explicitly
{ cout<< "print derived class" <<endl; }

void show ()
{ cout<< "show derived class" <<endl; }
};

//main function
int main()
{
base *bptr;
derived d;
bptr = &d;

//virtual function, binded at runtime (Runtime polymorphism)


bptr->print();

// Non-virtual function, binded at compile time


bptr->show();

return 0;
}
Output:

print derived class


show base class

You might also like