I currently practicing inheritance and I would like to understand how it works because is not working as expected.
What I have is two classes, Animal and Dog. In the code below I'm inheriting Animal to Dog and it works fine but when I try to do the oposite basically inherit Dog to Animal it doesn't work.
Can someone explain me why it doesnt work when trying to inherit atributes from Dog to Animal?
animal.h file
1 2 3 4 5
class Animal
{
public:
void eat();
};
dog.h file
1 2 3 4 5
class Dog: public Animal
{
public:
void bark();
};
Ok, I think I there is some confusion here, I'm only trying to inherit one at a time, thats why my confusion, why I can do it with one but not with the other.
I know the names I'm using dont make too much sense but I'm just practicing!
I know the names I'm using dont make too much sense but I'm just practicing!
The names you are using are just fine, but the problem is following:
One class can not inherit another class if that class does not see the actuall delaration of the class being inherited (I hope I got that English right)
The second prblem is that you also have to use include quards.
One class can not inherit another class if that class does not see the actuall delaration of the class being inherited (I hope I got that English right)
#pragma once
#include "dog.h"
class Animal
: public Dog
{
public:
void eat();
};
I would recommend you to learn about classes without inhritance first, also learn about organization of project files before you even thing about inheritance.
I found my problem, apparently the order of your includes determines who is the parent, I just moved the include for the dog.h to be before animal.h and it now works, of course now animal wont be able to inherit from dog which is totally fine, I was just trying to find the problem.
To answer my question, whichever class is included first it's the parent and any class included after can inherit from it, right?
Again the original question was:
What I have is two classes, Animal and Dog. In the code below I'm inheriting Animal to Dog and it works fine but when I try to do the oposite basically inherit Dog to Animal it doesn't work.
To answer my question, whichever class is included first it's the parent and any class included after can inherit from it, right?
No it's not. but C++ compilers do no lookaheads on names, so if you want to declare your class as inheriting from another one, that classes name (and declaration) already has to be known at that point.