Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
228 views
in C++ by (110k points)
Discover the power of C++ inheritance and unlock the potential of object-oriented programming. Learn how to create hierarchies of classes, reuse code efficiently, and build complex software systems. Gain insights into single inheritance, multiple inheritance, and the virtual keyword. Enhance your understanding of polymorphism, encapsulation, and code reusability. Explore real-world examples and practical tips to master C++ inheritance and elevate your programming skills. Start your journey now!

Please log in or register to answer this question.

2 Answers

0 votes
by (110k points)

Introduction to C++ Inheritance

Inheritance is one of the key features of object-oriented programming (OOP) languages like C++. It allows you to create new classes, known as derived classes or subclasses, based on existing classes, known as base classes or superclasses. The derived class inherits the properties and behavior of the base class, enabling code reuse and promoting a hierarchical relationship between classes.

In this tutorial, we'll cover the following topics:

  1. Basic Syntax of Inheritance
  2. Types of Inheritance
  3. Access Specifiers
  4. Constructors and Destructors in Inheritance
  5. Function Overriding
  6. Example Code

1. Basic Syntax of Inheritance

In C++, inheritance is denoted by a colon (:) followed by the access specifier and the name of the base class. The basic syntax is as follows:

class DerivedClass : access-specifier BaseClass {
   // class members and functions
};
 

The access specifier can be either public, protected, or private, determining the visibility and accessibility of the base class members in the derived class.

2. Types of Inheritance

There are several types of inheritance, including:

  • Single Inheritance: A derived class inherits from a single base class.
  • Multiple Inheritance: A derived class inherits from multiple base classes.
  • Multilevel Inheritance: A derived class becomes the base class for another derived class.
  • Hierarchical Inheritance: Multiple derived classes inherit from a single base class.
  • Hybrid Inheritance: A combination of multiple inheritance and multilevel inheritance.

For the purpose of this tutorial, we'll focus on single inheritance.

3. Access Specifiers

Inheritance introduces access specifiers that control the visibility and accessibility of the base class members in the derived class. There are three access specifiers:

  • public: The public members of the base class become public members of the derived class.
  • protected: The protected members of the base class become protected members of the derived class.
  • private: The base class's members are inaccessible directly in the derived class.

The choice of access specifier determines how the derived class can interact with the inherited members.

4. Constructors and Destructors in Inheritance

When working with inheritance, constructors and destructors play an important role. Here are some key points to consider:

  • Constructors: When creating an object of the derived class, the base class constructor is automatically called before the derived class constructor. This ensures that the base class members are properly initialized.
  • Destructors: The derived class destructor is called first, followed by the base class destructor. This ensures that resources allocated by the derived class are released before those allocated by the base class.

5. Function Overriding

Function overriding allows the derived class to provide its own implementation of a function inherited from the base class. The derived class redefines the function with the same signature as the base class. This enables polymorphism, where the appropriate function is called based on the object's type at runtime.

6. Example Code

Let's illustrate the concepts discussed above with an example code:

#include <iostream>

// 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() {
   Rectangle rect;
   
   rect.setWidth(5);
   rect.setHeight(10);
   
   int area = rect.getArea();
   
   std::cout << "Area: " << area << std::endl;
   
   return 0;
}
 

In this code, we have a base class Shape with two member variables width and height, along with their respective setter functions. The derived class Rectangle inherits from the Shape class using public inheritance. It adds a member function getArea() that calculates the area of the rectangle using the inherited width and height variables.

In the main() function, we create an object rect of the Rectangle class. We set the width and height of the rectangle using the inherited setWidth() and setHeight() functions. Finally, we calculate the area using the getArea() function and display it on the console.

This example demonstrates how the derived class Rectangle inherits the properties and behavior of the base class Shape through the public access specifier, allowing us to reuse code and extend functionality.

0 votes
by (110k points)

FAQs on C++ Inheritance

Q: What is inheritance in C++? 

A: Inheritance is a fundamental concept in object-oriented programming that allows you to define a new class (derived class) based on an existing class (base class). The derived class inherits the properties and behaviors of the base class, allowing code reuse and the creation of class hierarchies.

Example:

class Shape {
public:
    void setColor(string color) {
        this->color = color;
    }

    void draw() {
        cout << "Drawing a shape." << endl;
    }

private:
    string color;
};

class Circle : public Shape {
public:
    void draw() {
        cout << "Drawing a circle." << endl;
    }
};

int main() {
    Circle circle;
    circle.setColor("Red");
    circle.draw();

    return 0;
}
 

In this example, Circle is a derived class that inherits from the Shape base class. The derived class overrides the draw function to provide a specialized implementation for circles.

Q: What are the access specifiers used in inheritance? 

A: In C++, you can specify the access level for the inherited members using access specifiers: public, protected, or private. The default access specifier for inheritance is private.

Example:

class Base {
public:
    int publicMember;
protected:
    int protectedMember;
private:
    int privateMember;
};

class Derived : public Base {
    // publicMember is still accessible as public
    // protectedMember is still accessible as protected
    // privateMember is not accessible from derived class
};

int main() {
    Derived d;
    d.publicMember = 1;       // Accessible as public
    d.protectedMember = 2;    // Accessible as protected
    // d.privateMember = 3;   // Not accessible

    return 0;
}
 

In this example, the publicMember and protectedMember of the base class are accessible in the derived class based on their access specifiers.

Q: What is the order of constructor and destructor invocation in inheritance? 

A: In C++, when creating an object of a derived class, the base class constructor is invoked before the derived class constructor, and the destructor order is the reverse.

Example:

class Base {
public:
    Base() {
        cout << "Base constructor called." << endl;
    }

    ~Base() {
        cout << "Base destructor called." << endl;
    }
};

class Derived : public Base {
public:
    Derived() {
        cout << "Derived constructor called." << endl;
    }

    ~Derived() {
        cout << "Derived destructor called." << endl;
    }
};

int main() {
    Derived d;  // Output: Base constructor called. Derived constructor called. Derived destructor called. Base destructor called.

    return 0;
}
 

In this example, the base class constructor is invoked first, followed by the derived class constructor. During object destruction, the derived class destructor is called first, followed by the base class destructor.

Important Interview Questions and Answers on C++ Inheritance

Q: What is inheritance in C++? 

Inheritance is a mechanism in C++ that allows a class to inherit properties (data members and member functions) from another class. The class that is inherited from is called the base class, and the class that inherits is called the derived class.

Example:

class BaseClass {
public:
    void display() {
        cout << "Base Class" << endl;
    }
};

class DerivedClass : public BaseClass {
};

int main() {
    DerivedClass obj;
    obj.display(); // Output: Base Class
    return 0;
}
 

Q: What are the types of inheritance in C++? 

In C++, inheritance can be of the following types:

  • Single inheritance: A derived class inherits from a single base class.
  • Multiple inheritance: A derived class inherits from multiple base classes.
  • Multilevel inheritance: A derived class becomes the base class for another derived class.
  • Hierarchical inheritance: Multiple derived classes inherit from a single base class.
  • Hybrid inheritance: Combination of multiple inheritance and single inheritance.

Q: How is access control specified in inheritance in C++? 

In C++, access control in inheritance is specified using access specifiers:

  • Public inheritance: Public members of the base class become public members of the derived class, protected members become protected, and private members are inaccessible.
  • Protected inheritance: Public and protected members of the base class become protected members of the derived class, private members are inaccessible.
  • Private inheritance: Public and protected members of the base class become private members of the derived class, private members are inaccessible.

Q: What is function overriding in inheritance in C++? 

Function overriding occurs when a derived class defines a function that is already present in its base class. The derived class provides a different implementation of the function. It allows polymorphic behavior.

Example:

class BaseClass {
public:
    virtual void display() {
        cout << "Base Class" << endl;
    }
};

class DerivedClass : public BaseClass {
public:
    void display() {
        cout << "Derived Class" << endl;
    }
};

int main() {
    DerivedClass obj;
    obj.display(); // Output: Derived Class
    BaseClass* basePtr = &obj;
    basePtr->display(); // Output: Derived Class (Polymorphism)
    return 0;
}
 

Q: What is the difference between function overloading and function overriding in C++?

  • Function overloading: It allows multiple functions with the same name but different parameters in the same class. The functions are distinguished by their parameter types or the number of parameters.
  • Function overriding: It occurs when a derived class defines a function that is already present in its base class. The function signatures must be the same in the base and derived class for overriding.

Q: What is an abstract class in C++? 

An abstract class is a class that cannot be instantiated and is typically used as a base class. It contains one or more pure virtual functions, making it an incomplete class. Derived classes must implement these pure virtual functions to become concrete classes.

Example:

class AbstractClass {
public:
    virtual void display() = 0; // Pure virtual function
};

class ConcreteClass : public AbstractClass {
public:
    void display() {
        cout << "Concrete Class" << endl;
    }
};

int main() {
    ConcreteClass obj;
    obj.display(); // Output: Concrete Class
    return 0;
}

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jun 7, 2023 in C++ by kvdevika (110k points)

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...