Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demo use of OOP inheritance and use of Dynamic member to create new objects
#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
//Parent Class
class Animal
{
public:
string name;
string food;
int legs;
Animal();
~Animal();
void Naming();
//virtual void Eating(string food);
};
//Child Class
class Cats : public Animal
{
public:
Cats();
~Cats();
int toys;
void Playing();
//virtual void Meowing();
//virtual void Eating(string food);
};
//Constructor belonging to Animal class
Animal::Animal()
{
cout << "Animal class constructor called!" << endl;
name = "Default animal";
food = "Animal food";
legs = 4 ;
}
//Destructor belonging to Animal class
Animal::~Animal()
{
cout << "Animal class destroyer called!" << endl;
}
//Definition of member function Naming() in Animal class
void Animal::Naming() {
cout << "My name is " << name << endl;
}
//void Animal::Eating(string food) {
// cout << "My food is " << food << endl;
//}
//Constructor belonging to Cats class
Cats::Cats()
{
cout << "Cats class constructor called!" << endl;
name = "Cats";
food = "Cats food";
toys = 1;
}
//Destructor belonging to Cats class
Cats::~Cats()
{
cout << "Cats class destroyer called!" << endl;
}
//Definition of member function Playing() in Cat class
void Cats::Playing() {
cout << "I have " << toys << " toy(s)." << endl;
}
//void cats::meowing() {
// cout << "i love to meow!" << endl;
//}
//
//void cats::eating(string food) {
// cout << "i love to eat " << food << endl;
//}
int main()
{
Animal Generic_Animal;
Animal* pGeneric_Animal = &Generic_Animal;
pGeneric_Animal->Naming();
cout << "\n\n" << endl;
string Cat1food;
Cats* pCat1 = new Cats;
pCat1->name = "Garfield";
pCat1->Naming();
pCat1->Playing();
//pCat1->food = "Fish";
//pCat1->Naming();
//pCat1->Eating(Cat1food);
//pCat1->Meowing();
getchar(); //added to prevent console from closing after code is executed.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment