Appearance
Super / Parent Class Calls
In C++, there is no super keyword (unlike Java). Instead, you use the parent class name directly to call parent class methods or constructors.
1. Calling Parent Constructor
cpp
class Animal {
string name;
public:
Animal(string n) : name(n) {
cout << "Animal constructor: " << name << endl;
}
};
class Dog : public Animal {
string breed;
public:
Dog(string n, string b) : Animal(n), breed(b) { // calling parent constructor
cout << "Dog constructor: " << breed << endl;
}
};
// Output:
// Animal constructor: Bruno
// Dog constructor: LabradorParent constructor is called via initializer list using Animal(n).
2. Calling Parent Method
cpp
class Dog : public Animal {
public:
void sound() {
Animal::sound(); // calling parent method explicitly
cout << "Dog barks" << endl;
}
};
// Output:
// Animal makes a sound
// Dog barksUse ParentClassName::methodName() to call the parent method.
3. Default vs Parameterized Constructor
- If parent has a default constructor, it is called automatically — no need to explicitly call it.
- If parent has a parameterized constructor, you must call it explicitly via initializer list.
Common Mistake
cpp
class Animal {
public:
Animal(string name) { ... } // parameterized — no default!
};
class Dog : public Animal {
public:
Dog() { ... } // ERROR — parent has no default constructor
Dog() : Animal("Bruno") { ... } // CORRECT
};C++ vs Java vs Python Comparison
| C++ | Java | Python | |
|---|---|---|---|
| Keyword | No keyword | super | super() |
| Call parent constructor | Parent(args) in initializer list | super(args) | super().__init__() |
| Call parent method | Parent::method() | super.method() | super().method() |
Key Points
| Point | Detail |
|---|---|
| No super keyword | Use parent class name directly |
| Constructor call | Via initializer list Parent(args) |
| Method call | Via Parent::method() scope resolution |
| Default constructor | Called automatically |
| Parameterized constructor | Must call explicitly |
One-liner: "C++ has no super keyword — parent constructors are called via initializer list and parent methods via ParentClass::method() scope resolution operator."