Be the first to post for 'Dynamic vs Static Polymorphism'!

If you’re reading this, there probably aren’t very many posts yet. But don’t worry, you can be the first! Either create a new post or just reply to this one to say ‘hi’.

It may be a year and a half later, but…First!

I just wanted to mention that it’s good practice to check the validity of pointers passed to functions before attempting to call a method on them, for example:

void Stroke(Animal* animal)
{
    if (animal != nullptr) // or simply 'if (animal)'
    {
        animal->MakeNoise();
    }
}

Granted, Sam probably left this out of the lesson for simplicity and because instance pointers of Dog and Cat are passed in via address, but it’s best to get into the habit sooner rather than later. I’ve seen countless crashes because pointers passed to functions were not nullptr checked - either due to incorrect assumptions being made or the programmer simply forgot to do so.

Very true Pyro. I think I wasn’t in the habit yet at the time of recording but later content definitely does this all over the shop.

so on this topic, i thought it would be a neat idea to make another function similar to the GetSize() function and write something that would accept just the Animal object passed in, but i wanted it to print both the “base” of MakeNoise() and the ones for Cat/Dog. so i wrote something like this:

void Stroke(Animal animal)
{
	animal.MakeNoise();
	Animal& animalRef = animal;
	animalRef.MakeNoise();
};

But this just both returns “Animal noises”. Is there not some way to convert the object passed into a reference…? Or am i just clearly misunderstanding what is being fed into this Stroke method?

You are making a copy when you pass in to Stroke. And because the variable you are copying into is an Animal you are losing all the extra information that made it a Cat or Dog. So it would not be possible to cast it back.

Hi Sam,

So then is there no way to write the method that accepts all three types (regular object, pointer, reference)? Is there a way in C++ to check to see what is passed in is indeed either a pointer, reference, or regular object?

I wanted to write two maybe three methods that each accepts a different thing like in the GetSize() method

something like this?

void Stroke(Animal* animal)
{
	animal->MakeNoise();
};

void Stroke(Animal animal)
{
	animal.MakeNoise();
};

void Stroke(Animal& animal)
{
	animal.MakeNoise();
};

You can’t do this because C++ won’t know how to choose between the value and the reference version as the usage is exactly the same (it won’t depend on the type you pass in). This is deliberate as it gives the function the choice as to whether a copy should be made or not.

Privacy & Terms