while learning inheritance i came across a problem when trying to get a main class to inherit a sub class as if the main class is at the top the members of sub class wouldn't be seen:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//wrong
#include<iostream>
usingnamespace std;
class Main : public Sub {};
class Sub {
protected:
int Data;
public:
void Set_Data(int Data) { this->Data = Data; }
};
int main() {
Main Info;
Info.Set_Data(5);
return 0;
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//right
#include<iostream>
usingnamespace std;
class Sub {
protected:
int Data;
public:
void Set_Data(int Data) { this->Data = Data; }
};
class Main : public Sub {};
int main() {
Main Info;
Info.Set_Data(5);
return 0;
}
my question is is there a way to make the wrong way work without moving the class down in the code like in the right way and is it a good style to leave it in the top?
But why not do it the right way especially when you are only dealing with a couple of classes. Interestingly a lot of these sorts of problems don't arise when the system is planned before coding eg by a UML approach :)
> is there a way to make the wrong way work without moving the class down in the code like in the right way
No. The base class can't be an incomplete type. It must be defined before it is inherited from.
> is it a good style to leave it in the top?
In general, it is not good style to place the base class and the derived class in the same component.
The typical structure would be:
base_class.h - base class definition
base_class.cpp - base class implementation (#include base_class.h, right at the top, before other #includes)
derived_class.h - derived class definition (#include base_class.h)
derived_class.cpp - base class implementation (#include derived_class.h, right at the top, before other #includes)
With this separation into distinct components, the base class (and hence other components which use the base class interface) would not have a dependency on the derived class.
@JLBorges within the base_class implementation i need to add the : public derived_class and
than i can use the members of derived_class wile declaring a base_class object to manipulate them in main.cpp (with the definition of #include base_class.h and #include derived_class)?
example:
derived_class.cpp
1 2 3 4 5 6
class derived_class {
protected:
int data;
public:
void Set(int data) {this->data = data;}
};
base_class.cpp
1 2
#include derived_class.h
class base_class : public derived_class {};
main.cpp
1 2 3 4 5 6 7
#include derived_class.h
#include base_class.h
int main(){
base_class A
A.Set(5);
return 0;
if anything is missing or unnecessary please fix me, thanks in advance!
Java has super ( i.e. base) and sub (i.e. derived) where the sub-class (derived-class) inherits from the super-class (base-class). Come to think of it maybe parent and child might have been a better choice of words. :)