Skip to content

Instantly share code, notes, and snippets.

@lnrsoft
Created July 13, 2014 20:11
Show Gist options
  • Save lnrsoft/7e91d0e681a844d9603c to your computer and use it in GitHub Desktop.
Save lnrsoft/7e91d0e681a844d9603c to your computer and use it in GitHub Desktop.
This simple example consists of an overview of the syntax of inheritance in C++
// This source code written by Roland Ihasz
#include <iostream>
#include <string>
using namespace std;
class Animals { //base class
private:
string name;
int lifespan;
public:
Animals() {
name = "";
lifespan = 0;
}
Animals(string animalName, int animalLifespan) {
name = animalName;
lifespan = animalLifespan;
}
~Animals(){} // destructor
string getName(){
return name;
}
void setName(string animalName){
name = animalName;
}
int getLifespan(){
return lifespan;
}
void setLifespan(int animalLifespan){
lifespan = animalLifespan;
}
};
class Mammals : public Animals { // derived class
private:
string endangered;
public:
Mammals() : endangered("") {} // defult constructor
Mammals(string name, int lifespan, string isEndangered) : Animals(name, lifespan) { // constructor
endangered = isEndangered;
}
~Mammals(){} // destructor
string getEndangered(){
return endangered;
}
};
int main()
{
Animals animal1("Giant tortoise", 120);
Animals animal2("Reindeer", 12);
cout << "Name of mammal: " << animal1.getName() << endl
<< ">>lifespan: " << animal1.getLifespan() << endl;
cout << "Name of mammal: " << animal2.getName() << endl
<< ">>lifespan: " << animal2.getLifespan() << endl;
Mammals mammal1("Rhesus macaque", 25, "No, Least concern");
Mammals mammal2("Sumatran orangutan", 50, "Yes, Critically Endangered");
cout << "Name of mammal: " << mammal1.getName() << endl
<< ">>lifespan: " << mammal1.getLifespan() << endl
<< "Is endangered?: " << mammal1.getEndangered() << endl;
cout << "Name of mammal: " << mammal2.getName() << endl
<< ">>lifespan: " << mammal2.getLifespan() << endl
<< "Is endangered?: " << mammal2.getEndangered() << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment