Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,853 questions

51,774 answers

573 users

How to call multiple virtual functions using array of pointers in C++

1 Answer

0 votes
#include <iostream>

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

class Mammal {
public:
	virtual ~Mammal() { }
	virtual void Print() const { cout << "class Mammal" << endl; }
};

class Dog : public Mammal {
public:
	void Print()const { cout << "class Dog" << endl; }
};

class Cat : public Mammal {
public:
	void Print()const { cout << "class Cat" << endl; }
};

class Dolphin : public Mammal {
public:
	void Print()const { cout << "class Dolphin" << endl; }
};


int main()
{
	Mammal *arr[4], *p;

	p = new Dog;
	arr[0] = p;

	p = new Cat;
	arr[1] = p;

	p = new Dolphin;
	arr[2] = p;

	p = new Mammal;
	arr[3] = p;

	for (int i = 0; i < 4; i++)
		arr[i]->Print();

	return 0;
}

/*
run:

class Dog
class Cat
class Dolphin
class Mammal

*/

 



answered Apr 2, 2018 by avibootz

Related questions

1 answer 168 views
1 answer 139 views
1 answer 151 views
1 answer 151 views
1 answer 185 views
2 answers 51 views
...