I am learning c++, in particular, I am learning about inheritance. I wrote the following code where I wanted to print the contents of protected_stuff
, a variable defined within the protected
access specifier in the MainClass
.
Here is my code:
- inheritance.cpp
#include<iostream>
#include"MainClass.h"
#include"DerivedClass.h"
int main(){
DerivedClass a;
a.func();
return 0;
}
- DerivedClass.h
#ifndef DERIVEDCLASS
#define DERIVEDCLASS
class DerivedClass: public MainClass{
private:
int val;
protected:
int val2;
public:
int val3;
void func(void){
std::cout<<protected_stuff;
}
};
#endif
- MainClass.h
#ifndef MAINCLASS
#define MAINCLASS
class MainClass{
private:
int value;
char charecter;
value= 10;
charecter='a';
protected:
int protected_stuff;
protected_stuff = 2;
public:
int public_stuff;
public_stuff = 3;
};
#endif
When I try to run g++ -I . inheritance.cpp
I get the following errors:
In file included from inheritance.cpp:2:
MainClass.h:11:2: error: 'value' does not name a type
11 | value= 10;
| ^~~~~
MainClass.h:12:2: error: 'charecter' does not name a type
12 | charecter='a';
| ^~~~~~~~~
MainClass.h:16:2: error: 'protected_stuff' does not name a type
16 | protected_stuff = 2;
| ^~~~~~~~~~~~~~~
MainClass.h:21:2: error: 'public_stuff' does not name a type
21 | public_stuff = 3;
| ^~~~~~~~~~~~
Later I modified MainClass.h
and the code works fine.
#ifndef MAINCLASS
#define MAINCLASS
class MainClass{
private:
int value= 10;
char charecter='a';
// value= 10;
// charecter='a';
protected:
int protected_stuff= 2;
// protected_stuff = 2;
public:
int public_stuff = 3;
// public_stuff = 3;
};
#endif
My question is what was I doing wrong? I tried looking at various other questions on SO but couldn't find something similar:
- error: 'x' does not name a type
- error: ‘X’ does not name a type X in template functions
- "X does not name a type" error in C++
- "Y does not name a type" error in C++
- Error C++ : does not name a type
- Another "x" does not name a type error
- Correct place to initialize class variables?
- Initialisation and assignment