0
0
C++programming~5 mins

Base and derived classes in C++

Choose your learning style9 modes available
Introduction

Base and derived classes help organize code by sharing common features and adding new ones. This makes programs easier to build and understand.

When you want to create a general template for objects and then make specific versions.
When many objects share some behavior but also have unique features.
When you want to reuse code to avoid repeating the same parts.
When modeling real-world things that have common traits but differ in details.
When you want to improve your program step-by-step by adding new features.
Syntax
C++
class BaseClass {
public:
    // Base class members
};

class DerivedClass : public BaseClass {
public:
    // Additional members
};

The DerivedClass inherits from BaseClass using : public BaseClass.

Public inheritance means the derived class keeps the base class's public members accessible.

Examples
Here, Dog inherits eat() from Animal and adds bark().
C++
#include <iostream>

class Animal {
public:
    void eat() {
        std::cout << "Eating" << std::endl;
    }
};

class Dog : public Animal {
public:
    void bark() {
        std::cout << "Barking" << std::endl;
    }
};
Car is a Vehicle and can start() and honk().
C++
#include <iostream>

class Vehicle {
public:
    void start() {
        std::cout << "Vehicle started" << std::endl;
    }
};

class Car : public Vehicle {
public:
    void honk() {
        std::cout << "Car honks" << std::endl;
    }
};
Sample Program

This program shows a Student using a greeting from Person and its own study() method.

C++
#include <iostream>

class Person {
public:
    void greet() {
        std::cout << "Hello!" << std::endl;
    }
};

class Student : public Person {
public:
    void study() {
        std::cout << "Studying" << std::endl;
    }
};

int main() {
    Student s;
    s.greet();  // From base class
    s.study();  // From derived class
    return 0;
}
OutputSuccess
Important Notes

Derived classes get all public and protected members from the base class.

Private members of the base class are not accessible directly in the derived class.

Use public inheritance to keep base class interface visible.

Summary

Base classes hold common features.

Derived classes add or change features.

This helps organize and reuse code easily.