C++ Tutorial

C++ Inheritance

A derived class reuses a base class. Write the shared parts once, then specialize.

Write the shared parts once

A dog is an animal. A car is a vehicle. In C++ that sentence is a type relationship: the derived class gets the members of the base class, then adds or changes what is special.

You list the base after a colon: class Dog : public Animal. public here is the kind of inheritance. This tutorial uses public inheritance, which is the usual choice for “is-a”.

class Dog : public Animal

Animal has eat. Dog does not rewrite it. A Dog object can calleat because it inherited the method. It also has bark, which only dogs have.

Example

#include <iostream>
using namespace std;

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

class Dog : public Animal {
public:
  void bark() {
    cout << "woof" << endl;
  }
};

int main() {
  Dog d;
  d.eat();
  d.bark();
  return 0;
}

d.eat() runs the function defined on Animal. You did not copy it into Dog.

Calling a base method from the derived class

Inside a derived method you can call the base version with the scope operator:Animal::eat(). That is useful when the derived class wants the shared work plus extra steps.

Example

#include <iostream>
using namespace std;

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

class Dog : public Animal {
public:
  void eat() {
    Animal::eat();
    cout << "then wags tail" << endl;
  }
};

int main() {
  Dog d;
  d.eat();
  return 0;
}

Without Animal::, eat() inside Dog::eat would call itself and recurse until the program crashed. Name the base when you mean the base.

Derived classes add their own members

Inheritance is not only methods. The derived class can add fields. Keep those fields private on the derived class the same way you would on any class.

Example

#include <iostream>
#include <string>
using namespace std;

class Animal {
public:
  void sleep() {
    cout << "asleep" << endl;
  }
};

class Dog : public Animal {
private:
  string breed;

public:
  Dog(string b) {
    breed = b;
  }

  void show() {
    cout << breed << endl;
    sleep();
  }
};

int main() {
  Dog d("Beagle");
  d.show();
  return 0;
}

What public inheritance means

Base memberIn a public derived class
publicStill public. Callers can use it on the derived object.
protectedVisible to the derived class, not to outside code.
privateNot visible to the derived class. Use a public or protected base method instead.

Dog cannot read a private field of Animal directly. If the base needs to share a value with children only, mark it protected. Prefer private plus a method when you can.

Construct the base first

When you create a Dog, C++ constructs the Animal part first. If the base has a constructor that takes arguments, pass them in the member-initializer list.

Example

#include <iostream>
#include <string>
using namespace std;

class Animal {
private:
  string name;

public:
  Animal(string n) {
    name = n;
  }

  string getName() {
    return name;
  }
};

class Dog : public Animal {
public:
  Dog(string n) : Animal(n) {}

  void speak() {
    cout << getName() << " says woof" << endl;
  }
};

int main() {
  Dog d("Rex");
  d.speak();
  return 0;
}

Dog(string n) : Animal(n) {} forwards the name to the base. getName is a public method onAnimal, so Dog can call it.

Use inheritance for is-a

  • A dog is an animal. Inherit.
  • A car has an engine. Prefer a member, not inheritance.

Click Try it in C++ under an example to compile it at /cpp/try. That editor is not the Python page at /try. Next: the same animal types, but one function that works on all of them — polymorphism.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.

Physics

A shape, then a circle

Area is a shared idea. A circle specialises it as πr². Inheritance puts the name area() on the base and the formula on the derived class. For r = 2, A ≈ 12.57.

A = π r²

Example

#include <iostream>
using namespace std;

class Shape {
public:
  virtual double area() { return 0.0; }
};

class Circle : public Shape {
  double r;
public:
  Circle(double radius) : r(radius) {}
  double area() override { return 3.14159 * r * r; }
};

int main() {
  Circle c(2.0);
  cout << "A = " << c.area() << endl;
  return 0;
}

Biology

An animal, then a heart rate

Resting heart rate varies by species. A base Animal can report a default. Dog overrides it. 80 bpm is a typical resting dog; a greyhound at the track is faster.

Example

#include <iostream>
using namespace std;

class Animal {
public:
  virtual int resting_bpm() { return 0; }
};

class Dog : public Animal {
public:
  int resting_bpm() override { return 80; }
};

int main() {
  Dog d;
  cout << d.resting_bpm() << " bpm" << endl;
  return 0;
}

FAQ: C++ Inheritance

Common questions about this page.

What is the StudyGrid C++ tutorial?

The StudyGrid C++ tutorial is a full beginner-to-advanced track: syntax, types, input, loops, functions, classes, the STL, templates, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run c++ inheritance examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn c++ inheritance in this C++ C++ lesson (C++ Inheritance).

Is the C++ editor the same as Try Python or Try HTML?

No. Try C++ compiles with g++ at /cpp/try and shows stdout plus compiler messages. Try Python stays at /try. Try HTML stays at /html/try. C++ lessons never open those editors.

Do I need to install a compiler to learn C++?

No. Open a chapter, click Try it in C++, and compile in the browser. You can also download a .cpp file and compile locally with g++.

Where should I start the C++ tutorial?

Start at C++ Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open C++ Examples, then templates, map, and lambdas. Use Next at the bottom of each chapter.

Is the C++ tutorial free?

Yes. The C++ workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.