Skip to content

Instantly share code, notes, and snippets.

@suragch
Created May 6, 2022 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suragch/762e4d112fe2cd77019dd710930369fe to your computer and use it in GitHub Desktop.
Save suragch/762e4d112fe2cd77019dd710930369fe to your computer and use it in GitHub Desktop.
Inheritance example - passing objects in constructors
#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