0

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();

4
  • 8
    You forgot to #include "classB.h" Commented Jun 20, 2013 at 13:57
  • You need to sort out your includes and header files. I doubt this has anything to do with inheritance. Commented Jun 20, 2013 at 14:00
  • 1
    After you solve this, you can solve the following linker error by separating your implementations in cpp files ;) Commented Jun 20, 2013 at 14:01
  • Always solve the first reported problem first. Commented Jun 20, 2013 at 15:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry it was mistake. actually classB.cpp already exists. create classB.h and declare B in it.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.