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,938 questions

51,875 answers

573 users

How to use virtual copy constructor in C++

1 Answer

0 votes
#include <iostream>

#define SIZE 3

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

class Mammal {
public:
	Mammal() { cout << "Mammal constructor" << endl; }
	virtual ~Mammal() { }
	Mammal(const Mammal &m);
	virtual void Print() const { cout << "class Mammal: " << endl; }
	virtual Mammal *Copy() { return new Mammal(*this); }
protected:
};

Mammal::Mammal(const Mammal &m) {
	cout << "Mammal Copy Constructor" << endl;
}

class Dog : public Mammal {
public:
	Dog() { cout << "Dog constructor" << endl; }
	virtual ~Dog() { }
	Dog(const Dog & rhs);
	void Print()const { cout << "class Dog: " << endl; }
	virtual Mammal *Copy() { return new Dog(*this); }
};

Dog::Dog(const Dog &d) : Mammal(d) {
	cout << "Dog copy constructor" << endl;
}

class Cat : public Mammal {
public:
	Cat() { cout << "Cat constructor" << endl; }
	~Cat() { }
	Cat(const Cat &);
	void Print()const { cout << "class Cat: " << endl; }
	virtual Mammal *Copy() { return new Cat(*this); }
};

Cat::Cat(const Cat &c) : Mammal(c) {
	cout << "Cat copy constructor" << endl;
}

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

	cout << "new Dog:" << endl;
	p = new Dog;
	arr[0] = p;

	cout << endl  << "new Cat:" << endl;
	p = new Cat;
	arr[1] = p;

	cout << endl << "new Mammal:" << endl;
	p = new Mammal;
	arr[2] = p;
	cout << endl;

	Mammal *CopyArray[SIZE];
	for (int i = 0; i < SIZE; i++)
	{
		cout << "arr[i]->Print(): ";
		arr[i]->Print();
		cout << "arr[i]->Copy(): ";
		CopyArray[i] = arr[i]->Copy();
		cout << endl;
	}
	for (int i = 0; i < SIZE; i++)
	{
		cout << "CopyArray[i]->Print(): ";
		CopyArray[i]->Print();
		cout << endl;
	}

	return 0;
}

/*
run:

new Dog:
Mammal constructor
Dog constructor

new Cat:
Mammal constructor
Cat constructor

new Mammal:
Mammal constructor

arr[i]->Print(): class Dog:
arr[i]->Copy(): Mammal Copy Constructor
Dog copy constructor

arr[i]->Print(): class Cat:
arr[i]->Copy(): Mammal Copy Constructor
Cat copy constructor

arr[i]->Print(): class Mammal:
arr[i]->Copy(): Mammal Copy Constructor

CopyArray[i]->Print(): class Dog:

CopyArray[i]->Print(): class Cat:

CopyArray[i]->Print(): class Mammal:

*/

 



answered Apr 2, 2018 by avibootz
edited Apr 2, 2018 by avibootz

Related questions

1 answer 148 views
148 views asked Mar 23, 2018 by avibootz
1 answer 236 views
3 answers 166 views
166 views asked Jan 29, 2023 by avibootz
...