How to use abstract class in C++

1 Answer

0 votes
#include <iostream>

using std::cout;
using std::endl;

class Animal {
public:
	Animal(int age = 4);
	virtual void MakeSound() = 0;   // pure virtual function
	virtual void Print() const;
protected:
	int age;
};

Animal::Animal(int age) : age(age) {}
void Animal::Print() const {
	cout << "age: " << age << endl;
}

class Dog : public Animal {
public:
	Dog(int age = 6);
	virtual void MakeSound();
};

Dog::Dog(int age) : Animal(age) {}

void Dog::MakeSound() {
	cout << "dog bark" << endl;
}

class Cat : public Animal {
public:
	Cat(int age = 2);
	virtual void MakeSound();
};

Cat::Cat(int age) : Animal(age) {}

void Cat::MakeSound() {
	cout << "cat wail" << endl;
}

int main()
{
	Animal *p = new Dog();

	p->MakeSound();
	p->Print();
	delete p;

	p = new Cat();
	p->MakeSound();
	p->Print();
	delete p;

	return 0;
}

/*
run:

dog bark
age: 6
cat wail
age: 2

*/

 



answered Apr 1, 2018 by avibootz
edited Apr 1, 2018 by avibootz

Related questions

1 answer 192 views
1 answer 171 views
1 answer 202 views
1 answer 163 views
2 answers 375 views
375 views asked Jul 4, 2017 by avibootz
6 answers 367 views
367 views asked Apr 25, 2017 by avibootz
...