Created
May 6, 2022 03:13
-
-
Save suragch/762e4d112fe2cd77019dd710930369fe to your computer and use it in GitHub Desktop.
Inheritance example - passing objects in constructors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class Pet{ | |
protected: | |
string Name; | |
string Breed; | |
int Age; | |
Pet(string name, string breed, int age) | |
{ | |
Name = name; | |
Breed = breed; | |
Age = age; | |
} | |
public: | |
void Introduce() | |
{ | |
cout << "He is the " << Age << " year old " << Breed << " called " << Name << ".\n"; | |
} | |
string getName() { | |
return Name; | |
} | |
}; | |
class Dog : public Pet { | |
public: | |
string Characteristic; | |
Dog(string name, string breed, int age, string characteristic) : Pet(name, breed, age) | |
{ | |
Characteristic = characteristic; | |
} | |
void Information(){ | |
cout << "He is " << Characteristic << ".\n"; | |
} | |
}; | |
class GermanShepherd : public Dog { | |
Dog& DogFriend; | |
public: | |
GermanShepherd(string name, int age, string characteristic, Dog& dogFriend) : DogFriend{dogFriend}, Dog(name, "German Shepherd", age, characteristic) | |
{ | |
//DogFriend = dogFriend; | |
} | |
void Info(){ | |
cout << Name << " has a friend named " << DogFriend.getName() << ".\n"; | |
} | |
void biteFriend() { | |
DogFriend.Characteristic = "not so aggressive anymore"; | |
} | |
}; | |
int main() | |
{ | |
Dog arslan = Dog("arslan", "Mastiff", 2, "very aggressive"); | |
arslan.Introduce(); | |
arslan.Information(); | |
GermanShepherd fido = GermanShepherd("Fido", 1, "friendly", arslan); | |
fido.Introduce(); | |
fido.Info(); | |
fido.biteFriend(); | |
arslan.Information(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment