user1124236
user1124236

Reputation: 503

Pointer to abstract class

I have three classes. A, B, and C.

Class B is an abstract class.

Class A needs to call functions of Class B.

Class C is derived from class B and also needs to hold a pointer to Class A to call functions of class A.

Requirement 1:

A needs pointer to B. I know this can be achieved using "B being an abstract class, its not possible to create instances of it. Hence I'm creating an instance of C in A and using it to call B's functions. " But facing issues while creating C's instance.

Requirement 2:

Class C needs a pointer to class A to call its functions. How do I achieve this?

//A.h

class A
{
public:
    void fun1();
    void fun2();
private:
    // creating ptr to C because B is an abstract class
    C *m_ptrC;
};

//A.cpp

void A::fun1()
{
    m_ptrC->fun4();
}
void A::fun2()
{
    //some code
}



//B.h
class B
{
public:
    //pure virtual function
    void fun3() = 0;
    void fun4();
};


//B.cpp

void B::fun4()
    {
            //pure virtual hence C::fun3() gets called
        fun3();
    }



//C.h
class C:public B
{
public:
    //Overridden from B
    void fun3();

private:
    //Ptr to class A, to call fun
    A *ptrA;
};

//C.cpp
//Overridden from B
void C::fun3()
{
    ptrA->fun2();
}

How should ptrC and ptrA be initialized? Also I'm not sure of the forward declaration and file includes result in redifinition/incomplete type error.

Upvotes: 1

Views: 364

Answers (1)

Eric Fortin
Eric Fortin

Reputation: 7603

Without actual code that shows the problem, here is what I think happens:

1: You are including C.h in A.h and C.h in A.h. This is called a circular dependency. To avoid those, you need to use forward declaration. You basically declare the class and only include its header in the cpp file actually using it. So in A.h for example you could have:

class C;

class A
{

void fun1();

private:

C *ptrC = new C; 
};

And in A.cpp you can then include C.h.

Other problem might be missing include guards in your headers.


2: Pass A's instance(as a ref or pointer) to C constructor. Also use forward declaration here as well. Be cautious about lifetime of the objects.

Having cyclic dependencies like so is often more trouble than is worth. Try having an interface for A(so you can pass it to C without including A.h in C's translation unit) or use functors that are bound to A instance.


3: I don't really get why you have an interface to C if you're not using polymorphism but it may due to lacking real code.

Upvotes: 1

Related Questions