invalid covariant return type for ‘virtual....

hii ,
im studying polymorphism in c++ , i tried this code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>
using namespace std;
class Food {
public:
	void print() {
		cout << " Food" << endl;
	}
};
class DogFood: public Food {
public:
	void prints() {
		cout << " DogFood" << endl;
	}
};
class pet {
public:
	virtual pet GP() {
		cout << "gp pet" << endl;
		pet c;
		return c;
	}
	virtual void set(Food f){cout <<"pet food"<<endl;};
};
class dog: public pet {
public:
	virtual <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< her where i get the error 
	dog GP() {
		cout << "gp dog" << endl;
		dog c;
		return c;
	}
	virtual void set(DogFood f){cout <<"dog food"<<endl;}
};
/*
 void pl(pet* p){
 Food grass;
 pet papa= p->GP();
 p->set(grass);
 }
 */
int main() {
	cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
	//	dog lasy;
	//pl(&lasy);
	return 0;
}

but i get this error :
 
invalid covariant return type forvirtual dog dog::GP()’

why ?

please if you can explain a bit a lot :) thnx
Last edited on
I guess the error is about the fact that pet::GP returns a pet dog::GP instead returns a dog
You have already defined GP to return a type of "pet" and now you are redefining it to return a type of "dog". That's not allowed.

Pet is a base class. Pet is, by its nature, an abstract type (you cannot own a pet of type "pet"; you own a "dog" or a "goldfish"). Therefore, pet should be an abstract base class. But it isn't. You have provided implementations for functions that should not have any.

I would argue that GP should not exist at all. GP seems to be a factory function; why not just use a constructor?
your right it didn't cross my mind , but know i remembered ,
cause in template functions you can choose to vary between the function variables but not the return type .
as a result you can't define a function with two different return types .

thnx a lot
Topic archived. No new replies allowed.