Sie sind auf Seite 1von 15

What is Inheritance?

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.

//C++ program to apply inheritance


#include <iostream>

using namespace std;

// Base class
class Shape {
public:
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}

protected:
int width;
int height;
};

// Derived class
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};

int main(void) {
Rectangle Rect;

Rect.setWidth(5);
Rect.setHeight(7);

// Print the area of the object.


cout << "Total area: " << Rect.getArea() << endl;
return 0;
}

Output
Total area: 35
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)

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

Note : The private members in the base class cannot be directly accessed in the derived class,
while protected members can be directly accessed. For example, Classes B, C and D all contain
the variables x, y and z in below example. It is just question of access.

// C++ Implementation to show that a derived class


// doesn’t inherit access to private data members.
// However, it does inherit a full parent object
class A
{
public:
int x;
protected:
int y;
private:
int z;
};

class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A // 'private' is default for classes


{
// x is private
// y is private
// z is not accessible from D
};

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

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.

Syntax:
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;
class A
{
public:
int x;
void getx()
{
cout << "Enter value of x: "; cin >> x;
}
};
class B
{
public:
int y;
void gety()
{
cout << "Enter value of y: "; cin >> y;
}
};
class C : public A, public B //C is derived from class A and class B
{
public:
void sum()
{
cout << "Sum = " << x + y;
}
};

int main()
{
C obj1; //object of derived class C
obj1.getx();
obj1.gety();
obj1.sum();
return 0;
} //end of program

Output
Enter value of x: 2
Enter value of y: 5
Sum = 7

What is Polymorphism?

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 :
The reason for the incorrect output is that the call of the function area() is being set once by the
compiler as the version defined in the base class. This is called static resolution of the function
call, or static linkage - the function call is fixed before the program is executed. This is also
sometimes called early binding because the area() function is set during the compilation of the
program.

But now, let's make a slight modification in our program and precede the declaration of area() in
the Shape class with the keyword virtual so that it looks like this −

class Shape {
protected:
int width, height;

public:
Shape( int a = 0, int b = 0) {
width = a;
height = b;
}
virtual int area() {
cout << "Parent class area :" <<endl;
return 0;
}
};

After this slight modification, when the previous example code is compiled and executed, it
produces the following result –
Rectangle class area
Triangle class area
This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since
addresses of objects of tri and rec classes are stored in *shape the respective area() function is
called.

As you can see, each of the child classes has a separate implementation for the function area().
This is how polymorphism is generally used. You have different classes with a function of the
same name, and even the same parameters, but with different implementations.

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

Handling Exceptions

Exception is a way of handling errors that may occur while the program is running, like dividing
any number by zero. Exception handling is built upon three keywords: try, throw, and catch.

Try - a try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.

Throw − A program throws an exception when a problem shows up. This is done using
a throw keyword.

Catch − A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an exception.

Example of Exception Handling

#include <iostream>
using namespace std;

int main()
{
try
{
int momAge = 30;
int childAge = 34;

if(childAge > momAge)


{
throw 99;
}
}
catch (int x)
{
cout << "Child's age cannot be older than the mother's age, ERROR NUMBER: " << x << endl;
}
}

Overloading Operator
Operator overloading is an important concept in C++. It is a type of polymorphism in which an
operator is overloaded to give user defined meaning to it. Overloaded operator is used to perform
operation on user-defined data type. For example '+' operator can be overloaded to perform
addition on various data types, like for Integer, String(concatenation) etc .

Almost any operator can be overloaded in C++. However there are few operator which cannot be
overloaded. Operator that are not overloaded are follows:

 scope operator - ::
 sizeof
 member selector - .
 member pointer selector - *
 ternary operator - ?:
Operator Overloading Syntax:

Implementing Operator Overloading


Operator overloading can be done by implementing a function which can be:
1. Member Function
2. Non-Member Function
3. Friend Function

Operator overloading function can be a member function if the Left operand is an Object of that
class, but if the Left operand is different, then Operator overloading function must be a non-
member function.

Operator overloading function can be made friend function if it needs access to the private and
protected members of class.

Restrictions on Operator Overloading

Following are some restrictions to be kept in mind while implementing operator overloading.
1. Precedence and Associativity of an operator cannot be changed.
2. Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary
remains binary etc.
3. No new operators can be created, only existing operators can be overloaded.
4. Cannot redefine the meaning of a procedure. You cannot change how integers are added.
Example program of Operator Overloading

#include <iostream>
using namespace std;

class Test
{
private:
int count;

public:
Test(): count(5){}

void operator ++()


{
count = count+1;
}
void Display() { cout<<"Count: "<<count; }
};

int main()
{
Test t;
// this calls "function void operator ++()" function
++t;
t.Display();
return 0;
}

Output:

Count: 6

Example 2

#include <iostream>
using namespace std;
class Fraction
{
int num, den;
public:
Fraction(int n, int d) { num = n; den = d; }

// conversion operator: return float value of fraction


operator float() const {
return float(num) / float(den);
}
};

int main() {
Fraction f(2, 5);
float val = f;
cout << val;
return 0;
}
Output:
0.4

Enumerated Types

Enumerated type (enumeration) is a user-defined data type which can be assigned some limited
values. These values are defined by the programmer at the time of declaring the enumerated type.

When we assign a float value in a character value then compiler generates an error in the same
way if we try to assign any other value to the enumerated data types the compiler generates an
error. Enumerator types of values are also known as enumerators. It is also assigned by zero the
same as the array. It can also be used with switch statements.

For example: If a gender variable is created with value male or female. If any other value is
assigned other than male or female then it is not appropriate. In this situation, one can declare the
enumerated type in which only male and female values are assigned.
Syntax:
enum enumerated-type-name{value1, value2, value3…..valueN};

enum keyword is used to declare enumerated types after that enumerated type name was written
then under curly brackets possible values are defined. After defining Enumerated type variables
are created. It can be created in two types:-
1. It can be declared during declaring enumerated types, just add the name of the variable before
the semicolon.or,
2. Beside this, we can create enumerated type variables as same as the normal variables.

enumerated-type-name variable-name = value;

Enumerated Type
Example 1
#include <bits/stdc++.h>
using namespace std;

int main()
{
// Defining enum Gender
enum Gender { Male,
Female };

// Creating Gender type variable


Gender gender = Male;

switch (gender) {
case Male:
cout << "Gender is Male";
break;
case Female:
cout << "Gender is Female";
break;
default:
cout << "Value can be Male or Female";
}
return 0;
}

Output:
Gender is Male

Example 2

#include <bits/stdc++.h>
using namespace std;

// Defining enum Year


enum year { Jan,
Feb,
Mar,
Apr,
May,
Jun,
Jul,
Aug,
Sep,
Oct,
Nov,
Dec };
int main()
{
int i;

// Traversing the year enum


for (i = Jan; i <= Dec; i++)
cout << i << " ";

return 0;
}

Output:
0 1 2 3 4 5 6 7 8 9 10 11

Das könnte Ihnen auch gefallen