C++ Abstract classes and pure virtual functions

 /*

 * Abstract class: A class which does not contain implementation.
 *
 * abstract class must have at least one pure virtual function.
 *
 * Pure virtual function: It does not have body.
 * 	Syntax:
 * 		virtual void function_name(argument_list) = 0;
 *
 * 	C++ is supporting pure virtual destructor as well. However, this
 * 	is different from pure virtual function. Because, pure virtual
 * 	destructor must have function body.
 *
 */

#include <iostream>
using namespace std;

class Animal {
public:
	virtual void run() = 0;
	virtual void speak() = 0;

	// virtual destructor is recommended if there is any
	// virtual function in a class
	virtual ~Animal() {
	}
};

class Dog : public Animal {
public:
	virtual void speak() {
		cout << "Woof!" << endl;
	}
};

class Labrador: public Dog {
public:
	Labrador() {
		cout << "New Labrador" << endl;
	}
	virtual void run() {
		cout << "Labrador running" << endl;
	}
};

void test(Animal& a) {
	a.run();
}

int main() {

	// We can't create array of animals
	// Animal animals[5]; // This is compile-time error

	// We can create pointer of Animal
	Animal* p; // This is valid

	// We can create array of pointer of Animal
	Animal* animals[10]; // This is valid

	// We can create array of Labrador
	Labrador l[10]; // This is valid

	Labrador lab;
	lab.speak();
	lab.run();

	animals[0] = &lab;
	animals[0]->speak();

	test(*animals[0]);

	return 0;
}

Comments

Popular posts from this blog

OOP Assignment 3 helping materials

Square root Algorithm in C++

OOP lab 7 task solution