Professor Jimatura
Professor Jimatura

Reputation: 79

Casting from an abstract base class reference to derived class reference

I have following C++ code

AbstractClass_01.h

class AbstractClass_01 {
public:
    virtual void method_01() = 0;
};

AbstractClass_02.h

class AbstractClass_02 {
public:
    virtual void method_02() = 0;
};

ClassA.h

#include "AbstractClass_02.h"

class ClassA : public AbstractClass_02{
    public:
        void method_02();
        void method_03();
};

ClassA.cpp

#include "ClassA.h"

void ClassA::method_02() {}

void ClassA::method_03() {}

ClassB.h

#include "AbstractClass_01.h"
#include "AbstractClass_02.h"

class ClassB : public AbstractClass_01 {
public:
    ClassB(AbstractClass_02& _obj);
    void method_01();
private:
    AbstractClass_02 &obj;
};

ClassB.cpp

#include "ClassB.h"
#include "ClassA.h"

ClassB::ClassB(AbstractClass_02& _obj) : obj(_obj) {}

void ClassB::method_01() {
    static_cast<ClassA&>(obj).method_03();
}

main.cpp

#include "ClassA.h"
#include "ClassB.h"

int main(int argc, char** argv) {

    ClassA a;
    ClassB b(a);
    
    b.method_01();
    
    return 0;
}

My question is whether the casting which I have done in the ClassB::method_01 is common C++ construct whether it is a sign of wrong design?

EDIT:

The reason why the ClassB constructor accepts references to the AbstractClass_02 instead of the ClassA is that I need to pass references to various objects which all have common interface AbstractClass_02. The problem is that this interface doesn't contain the method_03. One possible solution could be to append that method into the interface AbstractClass_02 but that method isn't cohesive with the method_02.

Upvotes: 0

Views: 242

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22176

This is known as downcasting and is typically a sign of bad design. Based on the limited knowledge we have, it seems obvious that you should take ClassA in constructor instead of AbstractClass_01

#include "AbstractClass_01.h"
#include "ClassA.h"

class ClassB : public AbstractClass_01 {
public:
    ClassB(ClassA & _obj);
    void method_01();
private:
    ClassA &obj;
};

But we don't know your real problem and why did you decide to go with casting or accepting interface in the first place.

Upvotes: 2

Related Questions