Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

Inheritance in c++

using namespace std;
#include <string>

class Cat {
public:
    string name;    
    Cat() {
        this->name = "Garfield";        
    }    
    string sound(){ //implemented sound method from the interface
        return "Meow!";
    }
}; 
 
class Tiger : public Cat { //the variable 'name' and the method 'sound()' are inherited
public:
    Tiger() : Cat(){
        //calling the constructor in the base class, Cat
    }
    string sound(){ //overwriting the sound() method in Cat
        return "Roar!";
    } 
    string catSound() : Cat{
        return Cat::sound(); //calling the sound method from Cat, non-overwritten
    }
};
Source by syntaxdb.com #
 
PREVIOUS NEXT
Tagged: #Inheritance
ADD COMMENT
Topic
Name
6+2 =