I have created 3 classes - GrandMother, Mother and Daughter. I wrote a code such that the Daughter class inherits from the Mother class and the Mother class inherits from the GrandMother calss.
GrandMother.h :-
#ifndef GRANDMOTHER_H
#define GRANDMOTHER_H
class GrandMother
{
public:
GrandMother();
~GrandMother();
};
#endif // GRANDMOTHER_H
Mother.h :-
#ifndef MOTHER_H
#define MOTHER_H
class Mother: public GrandMother
{
public:
Mother();
~Mother();
};
#endif // MOTHER_H
Daughter.h :-
#ifndef DAUGHTER_H
#define DAUGHTER_H
class Daughter: public Mother
{
public:
Daughter();
~Daughter();
};
#endif // DAUGHTER_H
GrandMother.cpp :-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
GrandMother::GrandMother()
{
cout << "Grand Mother Constructor!!" << endl;
}
GrandMother::~GrandMother()
{
cout << "Grand Mother Deconstroctor" << endl;
}
Mother.cpp :-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
Mother::Mother()
{
cout << "Mother Constructor!!" << endl;
}
Mother::~Mother()
{
cout << "Mother Deconstroctor" << endl;
}
Daughter.cpp:-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
Daughter::Daughter()
{
cout << "Daughter Constructor!!" << endl;
}
Daughter::~Daughter()
{
cout << "Daughter Deconstroctor" << endl;
}
main.cpp :-
#include<iostream>
#include "Mother.h"
#include "Daughter.h"
#include "GrandMother.h"
using namespace std;
int main(){
//GrandMother granny;
//Mother mom;
Daughter baby;
}
When I am running the code, it's giving me the following error:-
error: expected class-name before '{' token
Can anyone plz tell me what part of my code is wrong.
CodePudding user response:
Your header are not self-contained, so you have to include them in right order:
#include "GrandMother.h"
#include "Mother.h"
#include "Daughter.h"
but it is fragile.
Right way is to make the header self contained:
#ifndef GRANDMOTHER_H
#define GRANDMOTHER_H
class GrandMother
{
public:
GrandMother();
~GrandMother();
};
#endif // GRANDMOTHER_H
#ifndef MOTHER_H
#define MOTHER_H
#include "GrandMother.h"
class Mother: public GrandMother
{
public:
Mother();
~Mother();
};
#endif // MOTHER_H
#ifndef DAUGHTER_H
#define DAUGHTER_H
#include "Mother.h"
class Daughter: public Mother
{
public:
Daughter();
~Daughter();
};
#endif // DAUGHTER_H