Jimm
Jimm

Reputation: 8515

c++ inheritance issue, base class pointer not able to point to sub class

I have a file called classA.h as shown below

#include <iostream>

using namespace std;

class A
{
public:
    virtual void doSomething();
};


void A::doSomething()
{
    cout << "inside A" << endl;
}

Then i have a ClassB.cpp as shown below

#include "classA.h"

class B : public A
{
 public:
    void doSomething();
};

void B::doSomething()
{
    cout << "class B" << endl;

}

Then i have classC.cpp as shown below

#include <iostream>
#include "classA.h"

using namespace std;

class C : public B
{
public:
    void doSomething();
};


void C::doSomething()
{
    cout << "classC" << endl;
}


int main()
{
    A * a =new C();

    a->doSomething();


    return 0;
}

When i compile as shown below, i get error

 g++ -Wall classB.cpp classC.cpp -o classC
 classC.cpp:7: error: expected class-name before '{' token
 classC.cpp: In function 'int main()':
 classC.cpp:21: error: cannot convert 'C*' to 'A*' in initialization

Since C inherits from B, which inherits from A, why cannot i say A * a = new C();

Upvotes: 0

Views: 113

Answers (2)

ArmanHunanyan
ArmanHunanyan

Reputation: 1015

The problem is that B is not visible in classC.cpp. Chrate file classB.cpp and move declaration of B there. Then include it in classC.cpp.

Upvotes: 1

Shar
Shar

Reputation: 455

You forgot to include "classB.h" in your main.cpp !

Upvotes: 0

Related Questions