How to access a child class function - c++

class base{}
class child : public base{
**dummyfunction();**
}
now I am calling a function in which I am passing a child class object.
**child ob;**
function(**ob**);//calling a function
//function body
function(**base *object**)
{
**//here I want to access the function of child class. How can I do it???**
**for example dummyfunction()**
}

You either need to put the function in the base class and make it virtual, or you need to do a type-safe down cast, using dynamic_cast. It is probably better to make the function a part of the interface, and have it available both in the base class and in the child class, but without more information it's hard to say. Generally speaking, though, the use of RTTI and dynamic_cast are indicative of poor design.

Why would you want to do this? If you're taking in an object of class base, you can't call a function of class child.

Your desires are contrary to the purpose of the data structures you're using.
You can do it with
child *child_object = dynamic_cast<child*>(object);
child_object -> dummyfunction();
but you shouldn't. Try designing your system properly instead.

In addition to using dynamic cast you can use static_cast with references:
base &b = base();
static_cast<child&>(b).dummyFunction();

What you required is downcasting.
you can acheive by making the dummyFunction as virtual in base class and then overriding this function in child class this solution would not require downcasting
otherwise you can use the method described in the below post but this is not safe to downcast
Downcasting Method

Suppose the function you want to call is
void f();
Make it virtual in Base class and override in Derived class and then call it from inside any member function of the Base class (except constructor!).

Related

C++ inheritance: Can't access child's member variables from parent class [duplicate]

I want to call a derived class function that isn't defined in the base class using base class pointers. but this always raises the error:
error C2039: ‘derivedFunctionName’ : is not a member of ‘BaseClass’
Do you know how I could get around this?
Thanks,
You can't call a member that appears only in a derived class through a pointer to the base class; you have to cast it (probably using dynamic_cast) to a pointer to the derived type, first -- otherwise the compiler has no idea the method even exists.
It might look something like this:
void someMethod(Base* bp) {
Derived *dp = dynamic_cast<Derived*>(bp);
if (dp != null)
dp->methodInDerivedClass();
}
One way is to make the function virtual in the base class and then override it in the derived class. You don't have to define the function in the base class (although you can), but you can use the pure virtual syntax in the base class virtual void foo() = 0; if you don't want to provide an implementation in the base class.
This will let you override it in the derived class and still call it in the base class through a base class pointer. This is known as 'polymorphism'.
You can also just cast it to a derived type at run time if you are sure it is actually a derived class pointer at that time. If it is not, it will crash.
You can call a derived class member through a pointer to a base class as long as the method is virtual. That's what polymorphism is about.
In order for that to work you must declare a virtual method (probably pure virtual) in the base class and overload it in the derived class.
Note that you will run into issues calling the derived member from the base method. Do some ARM or Meyers reading if this doesn't make sense to you.

casting pointer of base class to unknown subclass possible somehow?

Scenario:
BaseClass* pointer = &subClassXObject; // subClassXObject is object of class subClassX
// which is derived from BaseClass and
// Instance<subClassX>. (Instance<subClassX> is
// for counting instances of type subClassX.)
// Instance<subClassX> is derived from
// BaseInstance.
&... stands for getting an address, C++ Standard terminology might define object as being the address already, in this case &... is the object itself
The class of subClassXObject is unknown at this point, it can be any defined subclass of BaseClass.
It is known that it is one of the direct derived subclasses of BaseClass which each also inherit from Instance<subClassX> where subClassX is the name of the direct derived subclass of BaseClass.
Instance<subClassX> inherits from BaseInstance. BaseInstance defines a public pure virtual function which Instance<subClassX> implements, it's name is getDescriptor.
Thus every subClassObject has access to getDescriptor.
SubClassX* pointer = &subClassXObject;
pointer->getDescriptor(); // This should work
(Or does it not? Now I am riddling: do I have to explicitly implement a base class public method in a subclass in order for someone being able to call it upon the subclass from outside? No..., haven't I?).
I like
BaseClass* pointer = &subClassXObject;
pointer->getDescriptor();
to work.
Moving getDescriptor from BaseInstance and Instance<subClassX> to BaseClass and each sub class is possible, however I want users of my BaseClass to only write application logic code, not infrastructure code (even if they only would have to return an Instance<subClassX> methods return value). The idea behind this is to create an object browser into which every sub classes instantiated object is fed and listed without users having to add any non-classpurpose-code.
Casting pointer to BaseInstance* crashes the application. Thus my question as phrased in the title.
Thank you for your caring!
Just define the function in base class with virtual key word, and the right derived class will be pickup automatically.
class Base{
public:
virtual int getDescriptor();
};
Declare BaseClass* pointer as BaseInstance* pointer. Then a cast is not necessary and it works.
You can only use BaseInstance methods then as casting to BaseClass* would crash then. As the methods are used from the object browser this is about infrastructure functions, they make more sense in BaseInstance than in BaseClass, so not being able to use BaseClass methods is fine (BaseClass best contains base application logic methods only).

Virtual methods in constructor

Calling virtual methods in C++ is prohibited, however there are a few situations, where it might be very useful.
Consider the following situation - pair of Parent and Child classes. Parent constructor requires a Child class to be instantiated, because it has to initialize it in a special way. Both Parent and Child may be derived, such that DerivedParent uses DerivedChild.
There's a problem, however - because in Parent::ctor call from DerivedParent::ctor, base class should have an instance of DerivedChild instead of Child. But that would require calling a virtual method some way, what is prohibited. I'm talking about something like this:
class Child
{
public:
virtual std::string ToString() { return "Child"; }
};
class DerivedChild : public Child
{
public:
std::string ToString() { return "DerivedChild"; }
};
class Parent
{
protected:
Child * child;
virtual Child * CreateChild() { return new Child(); }
public:
Parent() { child = CreateChild(); }
Child * GetChild() { return child; }
};
class DerivedParent : public Parent
{
protected:
Child * CreateChild() { return new DerivedChild(); }
};
int main(int argc, char * argv[])
{
DerivedParent parent;
printf("%s\n", parent.GetChild()->ToString().c_str());
getchar();
return 0;
}
Let's get a real-world example. Suppose, that I want to write wrapper for WinApi's windows. The base Control class should register class and instantiate a window (eg. RegisterClassEx and CreateWindowEx), to properly set it up (for example register class in such way, that window structure has additional data for class instance; set up generic WndProc for all Controls; put reference to this by SetWindowLongPtr etc.)
On the other hand, derived class should be able to specify styles and extended styles, class name for window etc.
If constructing instance of window in the Control's constructor is a contract to be fulfilled, I see no other solution than to use VMs in ctor (what won't work).
Possible workarounds:
Use static polymorphism (eg. class Derived : public Base), but it will not work, if one wants to derive from Derived;
Pass a lambda from derived to base ctor if it is possible - it will work, but it's a total hardcore solution;
Pass a ton of parameters from derived to base ctor - it shall work, but won't be neither elegant, nor easy to use.
I personally don't like neither of them. Out of curiosity, I checked, how the problem is solved in Delphi's VCL, and you know what, base class calls CreateParams, which is virtual (Delphi allows such calls and guarantees, that they are safe - class fields are initialized to 0 upon creating).
How can one overcome this language restriction?
Edit: In response to answers:
Call CreateChild from the derived constructor. You're already requiring CreateChild to be defined, so this is an incremental step. You can add a protected: void init() function in the base class to keep such initialization encapsulated.
It will work, but it's not an option - quoting the famous C++ FAQ:
The first variation is simplest initially, though the code that actually wants to create objects requires a tiny bit of programmer self-discipline, which in practice means you're doomed. Seriously, if there are only one or two places that actually create objects of this hierarchy, the programmer self-discipline is quite localized and shouldn't cause problems.
Use CRTP. Make the base class a template, have the child supply the DerivedType, and call the constructor that way. This kind of design can sometimes eliminate virtual functions completely.
It's not an option, because it will work only once, for base class and its immediate descendant.
Make the child pointer a constructor argument, for example to a factory function.
This is, so far, the best solution - injecting code into base ctor. In my case, I won't even need to do it, because I can just parametrize base ctor and pass values from the descendant. But it will actually work.
Use a factory function template to generate the child pointer of the appropriate type before returning a parent. This eliminates the complexity of a class template. Use a type traits pattern to group child and parent classes.
Yea, but it has some drawbacks:
Someone, who derives from my classes may publish his ctor and bypass the security measures;
It would prevent one from using references, one would have to use smart pointers.
Calling virtual methods in C++ is prohibited, however there are a few situations, where it might be very useful.
No, calling a virtual method in the constructor dispatches to the most-derived complete object, which is the one under construction. It's not prohibited, it's well-defined and it does the only thing that would make sense.
A C++ base class is not allowed to know the identity of the most derived object, for better or worse. Under the model, the derived object doesn't start to exist until after the base constructors have run, so there's nothing to get type information about.
Some alternatives in your case are:
Call CreateChild from the derived constructor. You're already requiring CreateChild to be defined, so this is an incremental step. You can add a protected: void init() function in the base class to keep such initialization encapsulated.
Use CRTP. Make the base class a template, have the child supply the DerivedType, and call the constructor that way. This kind of design can sometimes eliminate virtual functions completely.
Make the child pointer a constructor argument, for example to a factory function.
Use a factory function template to generate the child pointer of the appropriate type before returning a parent. This eliminates the complexity of a class template. Use a type traits pattern to group child and parent classes.

Virtual class problem

What i think about virtual class is, if a derived class has a public base, let's say, class base, then a pointer to derived can be assigned to a variable of type pointer to base without use of any explicit type conversion. But what if, we are inside of base class then how can we call derived class's functions. I will give an example:
class Graph{
public:
Graph(string);
virtual bool addEdge(string,string);
}
class Direct:public Graph{
public:
Direct(string);
bool addEdge(string,string);
}
Direct::Direct(string filename):Graph(filename){};
When i call constructor of Direct class then it calls Graph. Now lets think Graph function calls addedge.
Graph(string str){
addedge(str,str);
}
When it calls addedge, even if the function is virtual, it calls Graph::edge. What i want is, to call Direct::addedge. How can it be done?
It can't be done. Virtual functions cannot be called whithin constructors -- at least they cannot be called with virtual behavior. The problem is that the derived class constructor is responsible for setting up the vtbl to point to it's particular instance of the virtual functions. The base class' constructor is executed first, before the derived constructor, so a direct solution to this is not possible.
You can work around this using either some form of "init" function on your base class, or you can use a factory method.
This is by design in C++, see the C++ FAQ.
In your case i also don't see why you would need it - if you want to use an initialization helper function, there is no need for it to be virtual.
Your explanation is here in Scott Meyer's Effective C++
Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor.
It appears you want your base type's constructor to call down into the derived type through a virtual method. This is troublesome as the derived type hasn't yet been fully constructed. What is the derived type's overridden virtual function going to use for state when its type hasn't yet been constructed? You might want to look into another design pattern, such as a factory, that can encapsulate the two-step construct/initialize pattern if you really need it.

Is there a way to "delete" a pure virtual function?

I have an abstract class with a couple pure virtual functions, and one of the classes I derive from it does not use one of the pure virtual functions:
class derivative: public base
{
public:
int somevariable;
void somefunction();
};
anyways, when I try to compile it, I get an error (apparently, a class is still considered abstract if derive from an abstract class and don't override all pure virtual functions). Anyways, it seems pointless to define a function
int purevirtfunc(){return 0;}
just because it needs to be defined through a technicality. Is there anyway to derive a class from an abstract class and not use one of the abstract class's pure virtual functions?
If your derived class doesn't "use" the base class pure virtual function, then either the derived class should not be derived from the base, or the PVF should not be there. In either case, your design is at fault and needs to be re-thought.
And no, there is no way of deleting a PVF.
A pure virtual class is an interface, one which your code will expect to be fulfilled. What would happen if you implemented that interface and didn't implement one of the methods? How would the code calling your interface know that you didn't implement the method?
Your options are:
Implement the method as you describe (making it private would indicate that it shouldn't be used).
Change your class hierarchy to take into consideration the design change.
The purpose of deriving from abstract classes is that external code can use the abstract class and expect that all functions have been implemented properly. Being able to unimplement a method would defeat this purpose, making the code uncompilable. You're free to throw an exception, if you so choose, however.
It's not a technicality at all. If your derived class does not exhibit all of the behavior of the parent, it should not be derived from the parent. This is a major design smell, and you probably need some design refactoring.
When you inherit from a class that has pure virtual functions, you MUST implement those functions. If you don't, then your derived class is also abstract, and you can't create an object of the derived class.
No. Either provide a default implementation in the base class or a simple implementation in the derived class, as you suggested.
There were already good answers, but if you want more info from the theoretical OO design side, check out the Liskov substitution principle.
Allowing this wouldn't make any sense. What would happen if you called the function without an implementation? A runtime error (that would be silly)? You could argue that it could a compile time error in some cases, but this is not possible if the exact type is not known (e.i. you pass a pointer to an instance of the derived class to a function).
As many people have already stated, it sounds like either the base method shouldn't be pure virtual or you should rethink whether your derived class really ISA base.
However, it is possible to provide an implementation for the pure virtual method in the base class. This can act like a default implementation for derived classes, but you still require the derived class to choose the base class's implementation explicity.
I don't know if that will help you with your problem or not.
No, there isn't. The convention in late bound languages when this situation occurs (as it legitimately might, but consider your design to see whether this method can be moved elsewhere, perhaps to its abstract class), is to raise an exception, and make sure that users of that method know that some implementations may raise that exception.
Seems i faced with the same problem, when trying to hide method getVertex() in derived class.
Maybe it's help.
class Body2D
{
public:
virtual ~Body2D() = default;
virtual double getCenter() const = 0;
virtual double getVertex() const = 0;
};
class Ellipse : public Body2D
{
public:
Ellipse(){};
double getCenter() const override{};
private:
double getVertex() const override{};
};
Couldn't you just do
class Foo {
public:
virtual void foo() = 0;
};
class Bar {
public:
virtual void foo() = delete;
};