C++ Casting From Parent to Child After Passing as a Function? - c++

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.

Related

dynamic cast with inheritance hierarchies

so I have this code:
Base* objbase = new Derived();
//perform a downcast at runtime with dynamic_cast
Derived* objDer = dynamic_cast<Derived*>(objBase);
if(objDer)//check for success of the cast
objDer->CallDerivedFunction();
This is a snippet of code for a cast operators section in my book.
Now why do I have this, I don't understand what's the point of having to dynamically cast a pointer to a base object pointing to a Derived object; For me, that's something to do with polymorphism giving us the ability to do objBase->DeriveClassFunction(), but I don't really know.
In the first place why does it do this: Base* objbase = new Derived();, and then why does it cast a base object pointer to a Derived again, I can't quite figure out why.
Thanks in advance.
That code snippet is just a demonstration of what's possible. It describes a tool, what you do with this tool is up to you. A slightly bigger example might be:
class Animal {
void Feed();
};
class Cat : public Animal { /*...*/ };
class Dog : public Animal {
// Only dogs need to go out for a walk
void WalkTheDog();
};
void Noon(Animal* pet)
{
// No matter what our pet is, we should feed it
pet->Feed();
// If our pet is a dog, we should also take it out at noon
Dog* dog = dynamic_cast<Dog*>(pet);
if(dog) // Check if the cast succeeded
dog->WalkTheDog();
}
Noon(new Cat()); // Feed the cat
Noon(new Dog()); // Feed the dog and take him out
Notice that every animal has the Feed() function, but only dogs have the WalkTheDog() function, so in order to call that function, we need to have a pointer to a dog. But it would also be quite a waste to copy the Noon() function for both types, especially if we might later add even more animals. So instead, the Noon() function works for any kind of animal, and does only the dog-specific things only if the animal is actually a dog.

Can someone explain the upcasting and downcasting syntax in terms of this code?

So, I'm on the last chapter of Programming for Games Module 1/2 and I ran into the code I've got below. I understand pointers are being created, I understand the first line of code, I pretty much understand what upcasting and downcasting are in concept, but I don't understand, specifically, what (Base*) and (Derived*) are doing here (the right hand sides of each line minus the first are confusing me).
Can someone just explain to me what this syntax is doing?
int main()
{
Derived* derived = new Derived();
Base* base = (Base*) derived; //upcast
Derived* derived2 = (Derived*) base; //downcast
return 0;
}
Consider the following statement:
int a = (int)(3.14);
This is called explicit type-casting. You basically tell the compiler, "I want to cast the float value 3.14 to an integer" which results in truncation of the decimal part and you get the value 3 i.e. the float value 3.14 is casted to an integer value 3. The compiler can perform such type-casting implicitly for fundamental data types.
Now consider the following:
Derived* derived = new Derived();
This creates a pointer of type Derived and dynamically allocates a new object of type Derived to it.
Now, the syntax:
Base* base = (Base*) derived;
This syntax is not really required as C++ allows that a derived class pointer (or reference) to be treated as base class pointer i.e. upcasting, but not the other way around as downcasting is a potentially dangerous operation.
The syntax however explicitly tells the compiler "I want to create a pointer of type Base and assign to it, the derived pointer which I have already created. Before assigning the value, I want to cast the type of pointer derived from type Derived to type Base and then assign it to base."
Please note that casting does not convert the type of pointer derived. The syntax above does not convert the type of pointer derived to Base. It only casts it into a Base pointer before assigning the value to base.
Similarly for the third line.
This is type-casting in C-Style. Although C++ supports C-Style type-casting, we have operators like static_cast, dynamic_cast etc in C++ which do a much better job. If you are wondering why we need such operators here is an excellent explanation :
Why use static_cast<int>(x) instead of (int)x?
Hope this clarifies your confusion.
Let's do an example. We have the following construction:
class Animal
{
public:
virtual string sound() = 0;
virtual ~Animal() {}
};
class Pig: public Animal
{
public:
string sound() override { return "Oink!"; }
};
class Cow : public Animal
{
public:
int milk; // made this public for easy code, but probably should be encapsulated
Cow() : milk(5) {}
string sound() override { return "M" + string(milk, 'o') + "!"; } // a Moo! with milk times many Os
};
What we now want to do is to store a list of animals. We can't use vector<Animal> because that would contain instances of the class Animal, which is purely abstract - Animal::sound is not defined.
However, we can use a vector of pointers:
vector<Animal*> animals;
animals.push_back(new Cow);
animals.push_back(new Pig);
animals.push_back(new Cow);
for(Animal* animal : animals)
{
cout << animal->sound() << endl;
}
So far, so good. But now take a look at the class Cow, there is the member milk which has an influence on the output. But how do we access it? We know that the first and third entries in animals are of type Cow, but can we use it? Let's try:
animals[0]->milk = 3;
This yields:
error: 'class Animal' has no member named 'milk'
However, we can do this:
Cow* cow = (Cow*) animals[0];
cow->milk = 3;
for(Animal* animal : animals)
{
cout << animal->sound() << endl;
}
What we done here is to create a pointer to Cow from a pointer to Animal of which we knew that it was actually pointing to an object of type Cow.
Note that this is risky - here, we knew that the first entry in the vector is of that type, but in general, you don't. Therefore, I recommend that you use safe casting, that is especially dynamic_cast. If you come to understood pointer casting and feel safe in that topic, read some tutorial on how to use dynamic_cast.
Right now, we have cast the base class to the derived class, but we can also do the opposite:
Cow* cow = new Cow;
cow->milk = 7;
animals.push_back((Animal*) cow);
for(Animal* animal : animals)
{
cout << animal->sound() << endl;
}
I assembled all of this into http://www.cpp.sh/6i6l4 if you want to see it in work.
Hope that this gives you a better understanding of what we need this for. Storing a list with objects of different types but a common base class is quite usual, and likewise is pointer to unknown subtypes. If you want more practical examples, ask. Thought about providing one, but don't want to overwhelm you for the start.
(Lastly, we need to clean up our memory, as we put our variables in the heap:
for(Animal* animal : animals)
{
delete animal;
}
animals.clear();
if we wouldn't do it, we'd have a memory leak. Better would have been to use smart pointers like shared_ptr - again here the recommendation to read into that when you feel safe in the base topic.)

Instantiating c++ interface as a child class

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);

Pass subclasses to a function that takes their superclass

Let's say I have three classes - Animal, Cat and Dog, where Cat and Dog are subclasses of Animal (this does sound like the first lectures, but it's not homework I promise, just simplifying the real code)
Dog* spike = new Dog();
Cat* puss = new Cat();
int main(int argc, char** argv)
{
function(spike, puss);
return 0;
}
void function(Animal *pet, Animal *pet2)
{
magic->andSoForth();
}
Now this generates the following error:
Cannot convert parameter 1 from 'Dog *' to 'Animal'
No constructor could take the source type,
or constructor overload resolution was ambiguous
Changing the parameters to exactly match generates similar errors, only that it says it can't convert from a class to the same class.
I have successfully called the subclasses functions and members that they inherit from the superclass, so I know that this, logically, should work. I just don't know in what twisted way this language want me to bend logic.
EDIT
Solution happen to be: pointers confuse everyone.
Declare pointers.
Send pointers as arguments to a function that does NOT handle pointers.
In my example, I sent the "not-pointers" to the function that wanted pointers, I just switched that. Now it works fine.
When you dynamically allocate a new object, you get a pointer to that object. So you need to store it in a pointer like so:
Dog* spike = new Dog();
Cat* puss = new Cat();
You can then pass spike or puss for any parameter of type Animal*, assuming Dog and Cat do indeed inherit from Animal. This is the basics of polymorphism in C++:
A prvalue of type “pointer to cv D”, where D is a class type, can be converted to a prvalue of type “pointer to cv B”, where B is a base class (Clause 10) of D.
You could, of course, have stored them right away as Animal*:
Animal* spike = new Dog();
Animal* puss = new Cat();
Don't forget to delete them. Better yet, don't use new at all:
Dog spike;
Cat puss;
void function(const Animal&, const Animal&);
function(spike, puss);
It's reasonable to assume that the problem you have is assigning a pointer to a non-pointer, or vice versa. But your code is not the real code, and your error messages are apparently not the real error messages. So it's all guesswork, in particular those already-posted answers that say "this is it" (it probably is, but not necessarily, and the uncertainty is entirely your own fault).
EDIT: the OP changed the question's code 10 seconds after I posted this.
The code still does not square with the purported error message.
I'm not going to chase this question as it changes.
Now, as to what to do…
Don't use new.
Experienced C++ programmers sometimes use new in controlled ways, wrapped in suitable code. Incompetent C++ programmers often use new as a matter of course. But in general, you don't need it, and it's problematic, so better as default don't use it.
Then, your program (which you neglected to show) would look like this:
#include <iostream>
struct Animal {};
struct Dog: Animal {};
struct Cat: Animal {};
void function(Animal const& pet1, Animal const& pet2 )
{
//magicAndSoForth();
}
int main()
{
Dog spike;
Cat puss;
function( spike, puss );
}
Your prototype for function almost certainly says
void function(Animal pet1, Animal pet2);
or something very similar to that. (I know you have a prototype, since function appears after main. If you hadn't forward-declared it, C++ would complain that it couldn't find function at all, not that it's taking the wrong types of args.)
Problem is, your real function takes pointers. And since main appears before the real function, it doesn't see that. It only sees a declaration of one that takes actual Animals, so it tries to use that...but fails, because an Animal pointer is not an Animal. (The real function differing from the prototype is fine with C++, due to the possibility of overloading. As far as the compiler knows, function(Animal, Animal) exists in another translation unit, and you're just defining function(Animal*, Animal*) too.)
Look through your code for the declaration of function, and make it say
void function(Animal *pet1, Animal *pet2);
to match up with the actual function's signature.
PS: this would have been so much easier to figure out if you had included all the relevant declarations.
PPS: A better idea would be to take references instead, as suggested by Alf. But in order to do that anyway, you'd have to fix the prototype mismatch (or make the real function appear before code that uses it) first
Well, what you need to do is this
Animal *spike = new Dog();
Animal *puss = new Cat();
Basically, all your pointer definitions must be of the base class, and these may be initialized with derived class pointers.
This is how it should look.
Dog* spike = new Dog();
Cat* puss = new Cat();
function(*spike, *puss);
void function(Animal pet, Animal pet2)
{
//magic
}
Tested and working.

Base class pointer vs inherited class pointer?

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.