I made a toy example of a problem I'm facing with my code:
I have an animal which I don't know what will be after a later stage, so I initialize it to a generic animal.
But later on, I want to make it a cat, so I'm assigning myAnimal to be a Cat
#include <iostream>
class Animal {
public:
int weight;
virtual void Sound() {
// To be implemented by child class
}
};
class Cat : public Animal {
public:
void Sound() {
std::cout << "Miau" << std::endl;
}
// Only cats purr
void Purr() {
std::cout << "Purr" << std::endl;
}
};
int main() {
// At this point I don't know which animal I'll have, so I initialize it
// to a generic Animal
Animal* myAnimal;
animal->weight = 10;
// At this point of the code, I know what animal I want, so I assign animal
// to be a Cat
double selectedAnimal = 0;
if (selectedAnimal == 0) {
myAnimal = &Cat();
// myAnimal = new Cat(); // this will just create a new Cat, losing
// the already assigned weight.
// I want to "upgrade" my generic animal, keeping its properties and adding
// new ones specific to cats
}
myAnimal->Sound();
myAnimal->Purr(); // ERROR: Class Animal has no member Purr
return 0;
}
I think I'm not assigning correctly myAnimal to be a Cat, but it is still an Animal. Howver the compiler doesn't complain when I do myAnimal = &Cat();.
So I don't understand if the compiler allows me to assign Animal to the class Cat myAnimal = &Cat(); why it complains when I try to use a method specific of the class Cat.
How should I reassign my generic animal in such a way that is now a full Cat with all its methods?
EDIT:
Answering some comments:
-Animal should not have a Purr method, only cats purr.
-I don't know at compile time what Animal will I have, that's why I assign it to be generic at the beginning.
I can reassign myAnimal to be a new Cat, but then any variables already set to the generic animal will be lost (eg: Animal might have a weight variable already set before knowing it's a Cat)
I'll try the suggested down-casting by #Some programmer dude
Firstly, when creating the Cat ensure that you allocate the memory correctly. Currently you are taking the address of a temporary object i.e. &Cat() which is not valid C++.
You can do this in two different ways:
// On the stack
Cat cat;
myAnimal = &cat;
// OR
myAnimal = new Cat(); // On the heap (remember to free the cat)
Then, when you want to use the animal as a cat, you can use a downcast e.g.:
auto myCatPtr = dynamic_cast<Cat*>(myAnimal);
if (myCatPtr) {
// This means the pointer is valid
myCatPtr->Purr();
}
Here is a working example.
The answer from Matthias GrĂ¼n shows how to manipulate C++ to do what you want.
However, my advice is to stop making C++ do what you think is right, and do it the way C++ wants to do it.
C++ wants you to never throw the type of an object away. It is a strongly-typed language. It almost always an "anti-pattern" to throw away the type of an object.
One common technique for avoiding this anti-pattern, is to separate "ownership" from "use". You can use a pointer to unknown-type, easily. Owning an object by a pointer to unknown type is really hard.
int main()
{
Cat my_cat;
Animal* any_animal = &my_cat; // non-owning pointer.
any_animal->Sound();
my_cat.Purr();
}
All that myAnimal = &Cat(); does is create a temporary of type Cat and assign the address of it to myAnimal, leaving you with a dangling pointer. myAnimal will point to an invalid address afterwards.
Also, even if it had been correctly assigned, for example by writing
myAnimal = new Cat{};
it would still require a cast so the compiler knows that it's dealing with a Cat, for example like so:
auto pCatInstance = dynamic_cast<Cat*>(myAnimal);
if (pCatInstance != nullptr)
pCatInstance->Purr();
Related
I was wondering if this (above title) is exactly possible when it comes to inheriting from an interface within C++.
class Animal
{
public:
virtual void Eat(Animal& a) = 0; //Function that attempts to eat an animal.
}
class Dog : Animal
{
public:
void Eat(Animal& a);
}
void Dog::Eat(Animal& a)
{
Dog d = (Dog) a;
// Do something.
}
int main()
{
Dog dog1 = Dog();
Dog dog2 = Dog();
dog1.Eat(dog2);
return;
}
So basically, I know that the animal that my dog is going to be eating is only other dogs (in all cases ever, not just in this specific example). However, I am inheriting from a purely virtual class Animal which requires me to define the function with the Animal parameter.
I know that having a parameter as Animal causes the function Dog::Eat to think that the parameter is an Animal and not a Dog. However, considering that the data for the object to be represented as a Dog is still there I am pretty sure that there is a way to establish (cast, etc) the Animal as a Dog, I just don't know how and I am not quite sure how to search.
So I am wondering how I would do this. I am pretty sure that you can use a dynamic cast or a reinterpret cast, but I am under the impression that you typically want to minimize the use of these casts if you can. I am pretty new to Object Oriented within C++ since I used to mainly use only C.
You can indeed cast it (assuming you intended Dog to be derived publicly from Animal); but you would have to cast a reference or pointer. Your cast to a value would try to create a new Dog from the Animal that was passed in; and there is no suitable conversion for that.
// safest, if you can't guarantee the type
Dog & d = dynamic_cast<Dog&>(a); // throws if wrong type
Dog * d = dynamic_cast<Dog*>(&a); // gives null if wrong type
// fastest, if you can guarantee the type
Dog & d = static_cast<Dog&>(a); // goes horribly wrong if wrong type
Don't use reinterpret_cast; that allows all sorts of crazy conversions, so it's easy to do something wrong. Don't use the C-style cast (Dog&)a either - that allows even more conversions than reinterpret_cast, and has a syntax that's subtle and difficult to search for.
In general, you shouldn't need a cast at all - try to design the base class so that it exposes everything you want to do with it, with no need to know the actual object type.
Weird behaviour of C++ pure virtual classes
Please help a bloody C++-beginner understand pure virtual classes better.
I tried a simple example with C++ virtuals and am not sure about the result.
If I tried the same in another programming language as java for example the output would be
Desired/Expected Output
1 -> Tweet
2 -> Tweet
However, here the output is
Actual Output
1 -> Meow
2 -> Tweet
Why is that?
It seems as if the operator= of the class animal had no effect.
Is that because a standard operator= of the class animal is called which just does nothing?
How would I achieve a behaviour similiar to java without having to use pointers?
Is that even possible?
Below an as simplified as possible example of code:
Code
#include <string>
#include <iostream>
using namespace std;
class Animal
{
public:
virtual string test() const = 0;
};
class Cat : public Animal
{
public:
virtual string test() const
{
return "Meow";
}
};
class Bird : public Animal
{
public:
virtual string test() const
{
return "Tweet";
}
};
void test_method(Animal &a)
{
Bird b;
a = b;
cout << "1 -> " << a.test() << endl;
cout << "2 -> " << b.test() << endl;
}
int main(int args, char** argv)
{
Cat c;
Animal &a = c;
test_method(a);
return 0;
}
Apparently, you have some unrealistic expectations about the behavior of a = b assignment.
Your a = b assignment simply copies data from Animal subobject of Bird object b to Animal subobject of Cat object referred by a. Since Animal has no data in it at all, you a = b is an empty operation, a no-op. It does not do anything at all.
But even if it did do something, it would simply copy the data fields. It cannot copy the polymorphic identity of the object. There no way to change the polymorphic identity of an object in C++. There's no way to change object's type. Regardless of what you do, a Cat will always remain a Cat.
The code you wrote can be shortened to
Cat a;
Bird b;
(Animal &) a = b; // Same as `(Animal &) a = (Animal &) b`
a.test(); // still a `Cat`
b.test(); // still a `Bird`
You did the same thing in a more obfuscated way.
In C++ references can't be rebound; they always refer to the variable you created them against. In this case a is a reference to c, and thus it is and will always be a Cat.
When you reassign a reference, you aren't rebinding the reference - you're assigning the underlying variable that the reference refers to. Thus the assignment a = b is the same as c = b.
You are a victim of what is known as object slicing. C++ is different from Java and C# in the way it handle its objects. In C# for example every user define type is managed as a reference when you create a new instance, and only primitive types and structures are handled as values, This means that in Java or C# when you assign an object, you are only assigning references, for instance:
Object a = new Object();
Object b = a;
Will result in both a and b pointing to the same object (The one created when we assigned a).
In C++ the story is different. you can create an instance of an object in the heap or the stack. and you can pass said objects by reference, by pointer or by value.
If you asssign references or pointers, it will behave similar to C# and Java. But if you assign an object by value, that is you assign the actual object and not a pointer or a reference, a new copy of the object will be created. Every user define type in C++ is copyable by default.
When you have inheritance and polymorphism involved, this copy behaviour creates an issue, because when you copy a child type into a parent type, the copy that will be created will only contains the portion of information for the parent type in the child, thus losing any polymorphism you may have.
In your example when you copy a Cat object into a Animal object, only the Animal part of the cat is copied, thats why you lose your polymorphism, the virtual table is no more. If you base class is abstract in any way this wont even be possible.
The solution, if you want to retain polymorphism, is to pass the object by pointer or reference instead of by value. You can create the object in the heap and assign that pointer, you can take the address of the object in the stack and assing that pointer, or you could just take the reference of the object and assign that instead.
The lesson to be learned here is to NEVER pass or assign by value objects with any sort of polymorphism or you will end up slicing it.
Try this.
#include <string>
#include <iostream>
using namespace std;
class Animal
{
public:
virtual string test() const = 0;
};
class Cat : public Animal
{
public:
virtual string test() const
{
return "Meow";
}
};
class Bird : public Animal
{
public:
virtual string test() const
{
return "Tweet";
}
};
void test_method(Animal *a)
{
Bird *b = new Bird();
a = b;
cout << "1 -> " << a->test() << endl;
cout << "2 -> " << b->test() << endl;
free(a);
}
int main(int args, char** argv)
{
Cat *c = new Cat();
Animal *a = c;
test_method(a);
free(c);
return 0;
}
Remove the a = b, and you'll get "Meow" followed by "Tweet"...
And in a bit more generic attitude:
First, define a generic interface for your generic class (Animal in this specific example).
You can then use this interface with any sub-class instance (Cat and Bird in this specific example).
Each instance will "act" according to your specific implementation.
Your mistake in function test_method was using an instance of the sub-class without referring to it through the generic class (with a reference or a pointer).
In order to change it into a generic function for Animal instances, you could do something like:
void test_method(Animal &a)
{
cout << a.test() << endl;
}
I have an interface, let's call it Creature, who has virtual functions that cause it to be abstract.
I have child classes of this interface such as Dog, Cat, and Pig.
The compiler doesn't seem to like the following line due to not being able to declare variable thing to be of abstract type Creature.
Creature thing = Dog();
I know I can't instantiate interfaces and the like, but this is just a Dog being declared as a Creature.
I need some way of having one declaration work for all the children (i.e., being able to put Dog(), Cat(), or Pig() where Dog() is in the line above).
Can this be done in c++ or am I misusing inheritance and interfaces completely?
Object types themselves are not polymorphic in C++. The line you've given declares a Creature object and then attempts to initialise it with a Dog object. If Creature weren't abstract, this would result in slicing - thing wouldn't be a Dog any more, it would just be a Creature. Since it is abstract, you simply can't have a Creature object anyway.
You need to use pointers or references for polymorphic behaviour. Consider for example:
Creature* thing = new Dog();
You can now dereference thing and use it as a Creature, even though it's dynamic type is Dog. However, using raw pointers like this is usually not recommended, as you have to manually ensure that the object is deleted at some point. The ownership can become confusing. Your best bet is to put it in a smart pointer, such as:
std::unique_ptr<Creature> thing(new Dog()); // or std::make_unique when we have it
Here, I've demonstrated std::unique_ptr, but the choice of smart pointer will depend on the ownership semantics for that object. A common alternative is std::shared_ptr.
To demonstrate polymorphism with references:
Dog dog;
Creature& thing = dog;
// Can now use dog as a Creature
In C++ you have to realize the different between value and reference semantics, where-as in interpretet languages you tend to just deal with reference semantics (except for some odd cases with plain old data objects which have value semantics but besides the point).
In C++ all objects are values, e.g an object can never be null, this has the implication that declaration specifies the storage requirement.
Consider the following
struct creature {
};
struct dog : public creature {
float cuteness;
};
The storage requirement for a dog is different than that of a creature, even if you allow the conversion this would result in slicing.
For example, will fido bark or be silent?
#include
class creature {
public:
virtual void speak() {
std::cout << "..." << std::endl;
}
};
class dog : public creature {
public:
virtual void speak() {
std::cout << "woof!" << std::endl;
}
};
int main(int argc, const char *argv[]) {
creature fido;
fido = dog();
fido.speak();
return 0;
}
However if you were to simply have a pointer or reference to the object it is a different matter.
By pointer.
creature* fido = new dog();
fido->speak();
delete fido;
By reference.
dog fido;
creature& c = fido;
c.speak();
Beyond the scope of this question, but optionally a smart pointer.
std::unique_ptr<creature> fido(new dog);
I am trying to create a vector of derived objects from within their base class.
class Animal
{
// Do Stuff
}
class Dog : public Animal
{
// Do Stuff
}
class AnimalKingdom
{
vector<Animal> animals;
vector<Dog> getDogs();
}
vector<Dog> AnimalKingdom::getDogs();
{
vector<Dog*> dogs;
for(i = 0; i < animals.size(); i++)
{
Animal& a = *animals[i];
if(typeid(a).name() == "class Dog")
{
dogs.push_back(*a);
}
}
}
But obviously *a isn't a pointer to a dog so it can't be added to dogs?
Does that make sense?
You need to type cast Animal into a Dog. Do some reading on what static_cast and dynamic_cast are. But generally static_cast is if you know what type you are converting to, and dynamic_cast is a guess and will return null if it not that type.
for(i = 0; i < animals.size(); i++)
{
Animal* a = &animals[i];
if(typeid(a).name() == "class Dog")
{
dogs.push_back(static_cast<Dog>(a));
}
}
Ps.Im at work so I cant check that code, looks rightish tho =D
First, typeid(a).name() will return a string that is compiler specific. In my gcc, for example, the returned string would be something totally different. Also, think of a third class that is subclass of Dog. Your typeid(a).name() would give you "class Chihuahua", which is a dog, but is not "class Dog".
You should use dynamic_cast for querying object type. When you do dynamic_cast<Dog*>(a) you are asking "can a be correctly casted to Dog?". If yes, you will have a pointer of type Dog*, if not you will have a NULL pointer.
Finally, at class AnimalKingdom , your vector is not going to allow you to have objects of type Dog. When you create a std::vector<Animal>, you are creating a vector whose elements are of fixed type sizeof(Animal). What you need is to work with pointers. A pointer points to a memory address without forcing this address to be of any size or of the base class.
Just to make it a bit more clear: When you do Animal a; you are creating a variable that is of the type Animal and has size sizeof(Animal). When you do Animal* a you are creating an memory address that has the size 4 bytes (or 8 bytes), for any pointer this will have this size. So it is possible that the Animal* points to something different than Animal, it may point to a subclass of Animal.
This is the difference between static allocation (fixed size) and dynamic allocation (dynamic size, but note that the pointer has a fixed size).
Your main problem is to understand you can not up-cast, This yields null. you can downcast the dog into animal and use only the min attributes of the parent though,
So this problem can be easily solved like:
1- return vector and use polymorphic flow to do whatever you want later.
2- make some bool or int to check or mark the kind of animal as below. e.g. make it 2 for dogs, This variable is defined in animal class. then use virtual functions to dynamically go to whatever you want at run time. so the below code can be good skeleton for you.
class Animal
{
int type;
virtual void setType()=0;
virtual int getType()=0;
};
class Dog :public Animal
{
void setType()
{
type = 2;
}
int gettype()
{
return type;
}
};
Have fun.
Suppose I have a class Dog that inherits from a class Animal. What is the difference between these two lines of code?
Animal *a = new Dog();
Dog *d = new Dog();
In one, the pointer is for the base class, and in the other, the pointer is for the derived class. But when would this distinction become important? For polymorphism, either one would work exactly the same, right?
For all purposes of type-checking, the compiler treats a as if it could point to any Animal, even though you know it points to a Dog:
You can't pass a to a function expecting a Dog*.
You can't do a->fetchStick(), where fetchStick is a member function of Dog but not Animal.
Dog *d2 = dynamic_cast<Dog*>(d) is probably just a pointer copy on your compiler. Dog *d3 = dynamic_cast<Dog*>(a) probably isn't (I'm speculating here, I'm not going to bother checking on any compiler. The point is: the compiler likely makes different assumptions about a and d when transforming code).
etc.
You can call virtual functions (that is, the defined polymorphic interface) of Animal equally through either of them, with the same effect. Assuming Dog hasn't hidden them, anyway (good point, JaredPar).
For non-virtual functions which are defined in Animal, and also defined (overloaded) in Dog, calling that function via a is different from calling it via d.
The answer to this question is a giant: It depends
There are numerous ways in which the type of the pointer could become important. C++ is a very complex language and one of the ways it shows up is with inheritance.
Lets take a short example to demonstrate one of the many ways in which this could matter.
class Animal {
public:
virtual void MakeSound(const char* pNoise) { ... }
virtual void MakeSound() { ... }
};
class Dog : public Animal {
public:
virtual void MakeSound() {... }
};
int main() {
Animal* a = new Dog();
Dog* d = new Dog();
a->MakeSound("bark");
d->MakeSound("bark"); // Does not compile
return 0;
}
The reason why is a quirk of the way C++ does name lookup. In Short: When looking for a method to call C++ will walk the type hierarchy looking for the first type which has a method of the matching name. It will then look for a correct overload from the methods with that name declared on that type. Since Dog only declares a MakeSound method with no parameters, no overload matches and it fails to compile.
The first line allow you to call only members of the Animal class on a :
Animal *a = new Dog();
a->eat(); // assuming all Animal can eat(), here we will call Dog::eat() implementation.
a->bark(); // COMPILATION ERROR : bark() is not a member of Animal! Even if it's available in Dog, here we manipulate an Animal.
Although (as pointed by others), in this cas as a is still an Animal, you can't provide a as a parameter of a function asking for a more specific child class that is Dog :
void toy( Dog* dog );
toy( a ); // COMPILATION ERROR : we want a Dog!
The second line allow you to use specific functions of the child class :
Dog *a = new Dog();
a->bark(); // works, but only because we're manipulating a Dog
So use the base class as the "generic" interface of your class hierarchy (allowing you to make all your Animals to eat() whithout bothering about how).
The distinction is important when you call a virtual function using the pointer. Let's say Animal and Dog both have functions called do_stuff().
If Animal::do_stuff() is declared virtual, calling do_stuff() on an Animal pointer will call Dog::do_stuff().
If Animal::do_stuff() is not declared virtual, calling do_stuff() on an Animal pointer will call Animal::do_stuff().
Here's a full working program to demonstrate:
#include <iostream>
class Animal {
public:
void do_stuff() { std::cout << "Animal::do_stuff\n"; }
virtual void virt_stuff() { std::cout << "Animal::virt_stuff\n"; }
};
class Dog : public Animal {
public:
void do_stuff() { std::cout << "Dog::do_stuff\n"; }
void virt_stuff() { std::cout << "Dog::virt_stuff\n"; }
};
int main(int argc, char *argv[])
{
Animal *a = new Dog();
Dog *b = new Dog();
a->do_stuff();
b->do_stuff();
a->virt_stuff();
b->virt_stuff();
}
Output:
Animal::do_stuff
Dog::do_stuff
Dog::virt_stuff
Dog::virt_stuff
This is just one example. The other answers list other important differences.
No, they aren't the same.
The Dog pointer is not as polymorphic as Animal. All it can point to at runtime is a Dog or a subclass of Dog. If there are no subclasses of Dog, then the Dog runtime type and compile time types are the same.
The Animal pointer can refer to any subclass of Animal: Dog, Cat, Wildebeast, etc.
The difference is important when you try to call Dog's methods that are not Animal's method. In the first case (pointer to Animal) you have to cast the pointer to Dog first. Another difference is if you happen to overload non-virtual method. Then either Animal::non_virtual_method() (pointer to Animal) or Dog::non_virtual_method(pointer to Dog) will be called.
You must always remember there are 2 parts in every class, the data and the interface.
Your code truly created 2 Dog objects on the heap. Which means the data is of Dog.
This object is of size the sum of all data members Dog + Animal + the vtable pointer.
The ponters a and d (lvalues) differ as from a interface point of view. Which determines how you can treat them code wise. So even though Animal* a is really a Dog, you could not access a->Bark() even if Dog::Bark() existed. d->Bark() would have worked fine.
Adding the vtable back into the picture, assuming the interface of Animal had Animal::Move a generic Move() and that Dog really overwriten with a Dog::Move() { like a dog }.
Even if you had Animal a* and performed a->Move() thanks to the vtable you would actually Move() { like a dog }. This happens because Animal::Move() was a (virtual) function pointer re-pointed to Dog's::Move() while constructing Dog().
It makes no real difference at run time, as the two instances are the same. The only difference is at compile time, where you could call for example d->bark() but not a->bark(), even if a actually contains a dog. The compiler considers the variable to be an animal and only that.