C++: Accessing variables present only in one of the derived classes - c++

void func1()
{
}
class Base
{
public:
virtual void memfunc() = 0;
};
class DerivedA: public Base
{
public:
virtual void memfunc() = 0;
};
class Derived1: public DerivedA
{
public:
void memfunc()
{
func1();
}
};
class Derived2: public DerivedA
{
public:
int* pbuf;
int val;
void func2(int* pbuf,int val)
{
/* update pbuf depending on the value of val*/
}
void memfunc()
{
func1();
func2(pbuf,val);
}
};
class user{
public:
Base* mBase;
void userfunc()
{
mBase = f(); //Object pointer to Derived1/Derived2 will be assigned based on dynamic loading;
//Before calling the below func, I Need to assign value to the 'val' variable of the class 'Derived2'
mBase->memfunc();
}
};
int main()
{
user ouser;
ouser.userfunc();
return 0;
}
The variables val and pbuf are present in Derived2 only.
How can I assign values to them in userfunc/main as I don't know if the object mBase would point to Derived1/Derived2.

You can use dynamic_cast and check for NULL, which will be returned if the object isn't of type Derived2. If the cast succeeds, you can use all methods of Derived2.

Use a dynamic_cast in userfunc() and test for Derived2, i.e.
Derived2* p = dynamic_cast<Derived2*>(mBase);
if (p) // this is NULL if the above fails.
{
// initialize...
}

If val and pbuf are present only on Derived2, then you must have some way to identify them. You would need to create an enum Base::Type { Derived1, Derived2 }, set them on your derived classes, and test in main. Then, you can cast mBase to Derived2 if it is of that type, and set val.

If you are sure of the concrete type of your class you can use a dynamic_cast. Anyway that's a bad practice. The purpose of using a base abstract class reference is to hide internal details and specific implementations issues.
If you need to do so, maybe you can add a getProperty()/setProperty() method to your base class. Something like:
class Base
{
public:
virtual void memfunc() = 0;
virtual void setProperty(String name, Property prop);
virtual Property getProperty(String name);
};

Use typeid:
http://en.wikipedia.org/wiki/Typeid

Related

C++ How to call a Child Method from Parent

I'm working on a small project, and I found myself in a situation like this :
class A{}
class B : class A {
public:
void f();
int getType() const;
private:
int type;
}
class C : class A{
public:
int getType() const;
private:
int type;
}
I want to know if there's a way to call the f() function (in class B) from an object of type A?
I tried this but it says function f() cannot be found in class A :
int main(){
vector<A*> v;
// v initialized with values of A ...
if (v->getType() == 1){ // 1 is the type of B
v->f();
}
}
As you've seen, this code won't compile because A doesn't have an f method. In order to make it work, you'd have to explicitly downcast the pointer:
B* tmp = dynamic_cast<B*>(v);
tmp->f();
To begin with, with your current classes, you can't call getType() on an A*. Because the interface of A doesn't have this method. To solve this problem, you either need to make getType a virtual function in A, or move the type field to base class A (as protected) and initialize it in the constructors of the child classes. Let me show you the first method, because I think it is a better approach, since it makes the objective of this function more clear.
class A {
public:
virtual int getType() { return 0; } // or delete the function: ... getType() = 0;
}
class B : public A {
public:
int getType() override { return 1; }
}
With these classes, once you create an instance of B, getType() returns 1 when called on that instance, whether it is pointed to by an A* or B*:
A *object = new B();
object->getType(); // returns 1
Now, if you need to access the f() from B, you can again add it as a virtual method to A's interface, or make a cast to B*.
Using a virtual method:
class A {
public:
virtual void f() { /* a default action maybe? */ }
}
class B : public A {
public:
void f() /* override if you want */ { /* whatever this function does in B */ }
}
...
for (A *ptr : v)
ptr->f();
Using a cast:
class A {
public:
virtual int getType() { return 0; }
}
class B : public A {
public:
void f();
int getType() override { return 1; }
}
...
for (A *ptr : v)
if (ptr->getType() == 1)
dynamic_cast<B*>(ptr)->f();

C++ force implementation of method in child class but with a different signature

Is there a way to force implementation of a method in a child class where the implementation will have a different signature for each derived class?
I know I can do this, using pure virtual:
class Base {
public:
virtual void getValue(string& s) = 0;
}
class Derived : public Base {
public:
void getValue(string& s);
}
Above, pure virtual getValue in the base class forces the derived class to implement getValue. But what I really want to do is something like this: Force each derived class to implement getValue() but each with a different signature:
class Base {
public:
void getValue() = 0;
}
class Derived_A : public Base {
public:
void getValue(string& s);
}
class Derived_B : public Base {
public:
void getValue(int *j);
}
The problem with the above is that, due to name mangling, each signature is effectively a different function, and thus Derived_A and Derived_B inherit getValue() = 0 and the compiler thinks that they also are abstract.
I've been playing around with some different ways to do this, but it appears to me there is no way to do it. I'm thinking I should simply not declare getValue in the Base class and then just make sure each derived class implements their version of it.
If use of CRTP would work for you, you can use:
#include <string>
template <typename TypeSelector>
class Base {
public:
using type = typename TypeSelector::type;
virtual void getValue(type t) = 0;
};
struct TypeSelector_A {
using type = std::string&;
};
class Derived_A : public Base<TypeSelector_A> {
public:
void getValue(std::string& s) { /* Add real implementation */ }
};
struct TypeSelector_B {
using type = int*;
};
class Derived_B : public Base<TypeSelector_B> {
public:
void getValue(int* j) { /* Add real implementation */ }
};
int main()
{
Derived_A a;
Derived_B b;
}
But what I really want to do is something like this: Force each derived class to implement getValue() but each with a different signature
The whole point of having virtual function (abstract or not) is that you can use it with pointer or reference to the base class which means you would use signature of the function from the base class. With that having what you want is completely useless. What you want can be implemented by returning std::variant or std::any with every virtual function in tree so keeping signature the same.
You should think how would you use such concept if it would be possible. If you think somethink like this:
void foo( Base *b ) {
if( auto *d = dynamic_cast<Derived_A *>( b ) ) {
std::string str;
d->getValue( str );
...
}
if( auto *d = dynamic_cast<Derived_B *>( b ) ) {
int i = 0;
d->getValue( &i );
...
}
}
then getValue() does not need to be virtual, you only need vritual destrictor in Base. But this is considered bad design.

How to avoid downcasting while having interface and base classes?

I'm sure i'm missing something elemental here, but i cannot get my head around it.
Let's say we have several possible implementations of a Managerclass which handles objects of type Base. It should be possible to define which implementation to use at runtime.
Based on the implementation of the Manager, they will have to set and get specific properties from Base, therefore the derivations DerivedA and DerivedB which they use internally. Is there a way to circumvent the need for downcasting the parameter in the Handle methods in order to get to the implementation-specific properties?
class Base { /* Abstract class with common properties */ };
class DerivedA : public Base { /* DerivedA-specific properties */ };
class DerivedB : public Base { /* DerivedB-specific properties */ };
class IManager { /* These functions must be implemented by every Manager implementation */
public:
virtual Base* Create() = 0;
virtual void Handle(Base*) = 0;
};
class AManager : public IManager
{
public:
Base* Create() override { return new DerivedA(); }
void Handle(Base* pFoo) override
{
// Now if we want to access pFoo's specific properties, we will need to dynamic_cast it
}
};
class BManager : public IManager
{
public:
Base* Create() override { return new DerivedB(); }
void Handle(Base* pBar) override { /* same here */ }
};
void Run(bool useAManager)
{
IManager* pManager = nullptr;
if (useAManager)
pManager = new AManager();
else
pManager = new BManager();
Base* pData = pManager->Create();
/* use Base specific properties ... */
pManager->Handle(pData);
}
Edit: Thank you all for the valuable input. I will accept #jpo38's post since it provides a possible solution to this problem. After some consideration however, I found that there is an underlying problem with the class design.
You can use the visitor pattern. In your example, this would be:
class DerivedA;
class DerivedB;
class Visitor
{
public:
virtual void visitA( DerivedA& a ) = 0;
virtual void visitB( DerivedB& b ) = 0;
};
class Base
{
public:
virtual void Accept( Visitor& visitor ) = 0;
};
class DerivedA : public Base
{
public:
virtual void Accept( Visitor& visitor ) { visitor.visitA( *this ); }
};
class DerivedB : public Base
{
public:
virtual void Accept( Visitor& visitor ) { visitor.visitB( *this ); }
};
Then, from AManager or BManager:
void Handle(Base* pFoo)
{
class MyVisitor : public Visitor
{
public:
virtual void visitA( DerivedA& a )
{
// do somethiong specific to a, you have access to DerivedA
}
virtual void visitB( DerivedB& b )
{
// do somethiong specific to b, you have access to DerivedB
}
};
MyVisitor v;
pFoo->Accept( v );
}
The disadvantage of visitor pattern is that you'll have to define a new visitor class every time you'll want to do something specific.
You can also consider doing this (but I definitely recommend visitors, very helful if you add DerivedC later or want to share some specific operation through shared visitor classes).
class Base
{
public:
virtual DerivedA* GetAsA() = 0;
virtual DerivedB* GetAsB() = 0;
};
class DerivedA : public Base
{
public:
virtual DerivedA* GetAsA() { return this; }
virtual DerivedB* GetAsB() { return NULL; }
};
class DerivedB : public Base
{
public:
virtual DerivedA* GetAsA() { return NULL; }
virtual DerivedB* GetAsB() { return this; }
};
Then, from AManager or BManager:
void Handle(Base* pFoo)
{
if ( pFoo->GetAsA() )
{
// use GetAsA to access DerivedA object avoiding downcasting
}
if ( pFoo->GetAsB() )
{
// use GetAsB to access DerivedB object avoiding downcasting
}
}
Not really. If you absolutely need to treat specific subtypes in a different way, dynamic_cast is the cleanest solution.
Strictly speaking, the real problem here starts at the word "properties". An object-oriented base class does not have properties but operations, and when you accept a Base parameter, all you are interested in are those abstract operations. In completely clean object-oriented designs, at least.
Your class design is just not cleanly object-oriented, that's all. But that's not a problem in itself. If it works for you and the code is easy to read and maintain, then everything is fine.

c++ design query

I am designing a framework in c++ which is supposed to provide basic functionality and act as interface for the other derived systems.
#include <stdio.h>
class Module
{
public:
virtual void print()
{
printf("Inside print of Module\n");
}
};
class ModuleAlpha : public Module
{
public:
void print()
{
printf("Inside print of ModuleAlpha\n");
}
void module_alpha_function() /* local function of this class */
{
printf("Inside module_alpha_function\n");
}
};
class System
{
public:
virtual void create_module(){}
protected:
class Module * module_obj;
};
class SystemAlpha: public System
{
public:
void create_module()
{
module_obj = new ModuleAlpha();
module_obj->print(); // virtual function, so its fine.
/* to call module_alpha_function, dynamic_cast is required,
* Is this a good practice or there is some better way to design such a system */
ModuleAlpha * module_alpha_obj = dynamic_cast<ModuleAlpha*>(module_obj);
module_alpha_obj->module_alpha_function();
}
};
main()
{
System * system_obj = new SystemAlpha();
system_obj->create_module();
}
Edited the code to be more logical and it compiles straight away. The question is, that is there a better way to design such a system, or dynamic_cast is the only solution. Also, if there are more derived modules, then for type-casting, there is some intelligence required in the base Module class.
If Derived is the only concrete instance of Base you could use static_cast instead.
Personally, I define a function, like MyCast for every specialized class. I define four overloaded variants, so that I can down-cast const and non-const pointers and references. For example:
inline Derived * MyCast(Base * x) { return static_cast<Derived *> (x); }
inline Derived const * MyCast(Base const * x) { return static_cast<Derived const *>(x); }
inline Derived & MyCast(Base & x) { return static_cast<Derived &> (x); }
inline Derived const & MyCast(Base const & x) { return static_cast<Derived const &>(x); }
And likewise for Derived2 and Base2.
The big advantage in having all four is that you will not change constness by accident, and you can use the same construct regardless if you have a pointer or a reference.
Of course, you could replace static_cast with a macro, and use dynamic_cast in debug mode and static_cast is release mode.
Also, the code above can easily be wrapped into a macro, making it easy to batch-define the functions.
Using this pattern, you could then implement your code as:
class Derived : public Base
{
public:
virtual void func2()
{
base2_obj = new Derived2();
}
void DerivedFunc()
{
MyCast(base2_obj)->Derived2Func();
}
}
The design gets much cleaner if Base does not contain the base_obj object, but rather gets a reference via a virtual method. Derived should contain a Derived2 object, like:
class Base
{
public:
virtual void func1();
private:
class Base2;
virtual Base2& get_base2();
};
class Derived : public Base
{
Derived2 derived2;
public:
Base2& get_base2() { return derived2; }
void DerivedFunc()
{
derived2->Derived2Func();
}
}
If you are worried about performance, pass the reference in the constructor of Base.
I took your code with its many compile errors and tried to simplify it. Is this what you are trying to acheive? It will compile.
class Base2 {
public:
virtual void Derived2Func(){
}
};
Base2* fnToInstantiateABase2();
class Base {
public:
Base() : base2_obj(fnToInstantiateABase2()) {
}
virtual void DerivedFunc() {
}
protected:
Base2* base2_obj;
};
class Derived : public Base {
public:
void DerivedFunc() {
base2_obj->Derived2Func(); // not possible as base2_obj is of type Base2
}
};
class Derived2 : public Base2 {
public:
void Derived2Func() {
}
};
void test() {
Base * base_obj = new Derived();
base_obj->DerivedFunc();
}
Base2* fnToInstantiateABase2() {
return new Derived2();
}

C++ Abstract type initialisation

I have a class Interface, that has pure virtual methods. In another class I have a nested type that inherits from Interface and makes it non-abstract. I use Interface as a type and use the function to initialise the type, but I am getting, cannot compile because of abstract type.
Interface:
struct Interface
{
virtual void something() = 0;
}
Implementation:
class AnotherClass
{
struct DeriveInterface : public Interface
{
void something() {}
}
Interface interface() const
{
DeriveInterface i;
return i;
}
}
Usage:
struct Usage : public AnotherClass
{
void called()
{
Interface i = interface(); //causes error
}
}
You use abstract classes as pointer and references, so you'd do
class AnotherClass
{
struct DeriveInterface : public Interface
{
void something() {}
}
DeriveInterface m_intf;
Interface &interface() const
{
return m_intf;
}
}
struct Usage : public AnotherClass
{
void called()
{
Interface &i = interface();
}
}
plus a couple of semicolons and it will work fine. Note that only pointers and references are polymorphic in C++, so even if Interface were not abstract, the code would be incorrect because of so-called slicing.
struct Base { virtual int f(); }
struct Der: public Base {
int f(); // override
};
...
Der d;
Base b=d; // this object will only have B's behaviour, b.f() would not call Der::f
You need to work with an Interface* here.