C++ new operator with valid vtable without calling constructor - c++

Is it possible to create an instance of a class on a heap without calling default constructor and with a valid vtable for inheritance? Let me demonstrate what I will like to do:
class A
{
protected: virtual void _fake_static_method()
{
}
};
class B1 : public A
{
protected: virtual void _fake_static_method()
{
std::cout << "Hello";
}
public: static void run_fake_static_method()
{
B1* dummy = static_cast<B1*>(::operator new(sizeof(B1)));
dummy->_fake_static_method();
free(dummy);
}
}
class B2 : public A
{
public: static void run_fake_static_method()
{
B2* dummy = static_cast<B2*>(::operator new(sizeof(B2)));
dummy->_fake_static_method();
free(dummy);
}
}
Here I want to call a static method from example B1::run_fake_static_method(). In that method I want to run a member method, but I don't want to call the default constructor. I need such an implementation to remove the virtual method without a compiling error among other errors. Like a "virtual static method" I hope you understand what I want to do.
Is there a special trick that I can get this to work? :)

Related

How does binding work for layered inheritance in C++?

Say I have a virtual class:
class Tester {
virtual void Validate();
}
class Test1 : Tester {
void Validate(...) {
/implementation
}
}
class Test2 : Test1 {
void Validate(...) {
/implementation
}
}
To my understanding, the virtual should make it dynamic binding. But I'm uncertain what would happen if we have layered classes (ie. Test2 inheriting Test1 inheriting Tester):
void RunTest(Tester test) {
test.Validate(...);
}
...
Test2 test_candidate = Test2();
RunTest(test_candidate)
Which Validate method would this call?
void RunTest(Tester test)
This parameter of the function is an object of type Tester. It isn't a Test1 nor is it a Test2, hence the call cannot be to anything other than Tester::Validate.
When you pass Test2 as an argument, it will be converted to Tester by copying the base sub object.
Virtual dispatch requires indirection. You must call the function through a reference or a pointer, because only a reference or a pointer can point to a base subobject of a derived object.
Answer to your question
(see below or here why your example code does not behave like this)
Behaviour of "late" binding
Late binding always invokes the most specialized virtual function of the instance-type. In your case, all classes, Tester, Test1 and Test2 would invoke their own Validate(), as Test and Test2 override this function in each subclass.
However, if you would have
Test3 : public Test1 { /* Not overriding Validate() */ }
calling Validate() on an instance of Test3 would call Test1::Validate(), as that is the most specialized virtual implementation (it overrides Tester::Validate()).
Problem in your example code
In your example code, the function RunTest(Tester) passes the argument by value. If you pass an argument of type Test1, it makes a temporary copy of type Tester, as indicated by other answers, and if your compiler allows it at all without warning. This temporary copy is used in RunTest(Tester) and will always call Tester::Validate(), and that might not be the implementation of the object you passed as an argument to RunTest(Tester).
To use late binding, you should pass a reference or a pointer:
RunTest(Tester *t) { t->Validate(); }
or
RunTest(Tester &t) { t->Validate(); }
Using one of these will ensure that the behaviour is as described above (your answer).
There are quite a few issues with the code you provided:
1. Private Inheritance + Private Function Definitions
You need to declare your methods as public to be able to call them from an external function like RunTest. Also you probably want to inherit publicly in this case, so you can cast your Test2 class back to a Tester.
e.g.:
class Tester {
public:
virtual void Validate();
};
class Test1 : public Tester {
public:
void Validate();
};
class Test2 : public Test1 {
public:
void Validate();
};
2. A few recommendations
If you want to override a virtual method in a child class, you can use override to mark your function as such. That way you'll get a compile-time error in case the function couldn't be overriden (e.g. because of mismatched arguments)
(I'm assuming you meant void Validate() {} instead of void Validate(...))
Also if your classes contain any virtual methods, it's always a good idea to also provide a virtual destructor. (to properly clean up all the members in case it gets deleted by a pointer to its baseclass)
e.g.:
class Tester {
public:
virtual void Validate() {
// TODO
}
virtual ~Tester() = default;
};
class Test1 : public Tester {
public:
void Validate() override {
// TODO
}
};
class Test2 : public Test1 {
public:
void Validate() override {
// TODO
}
};
3. The RunTest() function will slice the Test2 object
You're passing a Tester instance to RunTest() by value.
This will result in the object being sliced, i.e. you'll loose everything stored in the derived objects.
void RunTest(Tester test);
// this
Test2 t2;
RunTest(t2);
// is equivalent to:
Test2 t2;
Test t = t2;
RunTest(t);
so essentially you're calling the RunTest() method with just a Test object, not Test2.
you can fix this by either bassing by reference or by pointer:
void RunTest(Tester& test) {}
// or
void RunTest(Tester* test) {}
Working Example
#include <iostream>
class Tester {
public:
virtual void Validate() {
std::cout << "Tester Validate" << std::endl;
}
virtual ~Tester() = default;
};
class Test1 : public Tester {
public:
void Validate() override {
std::cout << "Test1 Validate" << std::endl;
Tester::Validate();
}
};
class Test2 : public Test1 {
public:
void Validate() override {
std::cout << "Test2 Validate" << std::endl;
Test1::Validate();
}
};
void RunTest(Tester& test) {
test.Validate();
}
int main() {
Test2 t;
RunTest(t);
}
test it on godbolt!

How to access data of mother class from child class?

How can I access data of the mother class from a child class without creating an instace?
I've got something like:
#include <iostream>
class mother {
private:
public:
mother(){}
virtual ~mother(){}
virtual void func() const {std::cout << "mother " << dat <<std::endl;}
virtual void dat_set(std::string arg){dat=arg;}
std::string dat;
};
class child:mother {
public:
child(){}
~child(){}
void dat_set(std::string const arg) override { mother::dat_set(arg); }
void func() const override { std::cout << "child " << mother::dat << std::endl; }
};
int main (void) {
auto tmp = new mother();
tmp->dat_set("test");
auto foo = new child();
foo->func();
}
How do I make sure that func() invoked by foo gets access to the data stored in mother?
EDIT
Should I not be able to make std::string dat a static std::string dat? I tried that but I get compiler errors along the lines of
/tmp/ccZV7Y4n.o: In function `child::func()':
main.cpp:(.text._ZN5child4funcEv[_ZN5child4funcEv]+0x1d): undefined reference to `mother::dat[abi:cxx11]'
The trick to accessing functions inside base classes from derived classes is to redeclare them using virtual and override specifiers...
First, make the destructor virtual... (Since your compiler doesn't want virtual functions inside a class without a virtual destructor)
virtual ~mother() = default; // If the compiler is happy, we all are happy...
And then make your functions virtual...
virtual void dat_set(std::string const arg) { dat = arg; }
virtual void func() const { std::cout << "mother " << dat << std::endl; }
You have to define it again inside the child class since the child cannot become the mother, and that is the reason you cannot access those functions...
void dat_set(std::string const arg) override { mother::dat_set(arg); }
void func() const override { mother::func(); }
Here you have to have the exact same declaration you had in the base class (except virtual which is redundant when override is used...) and add override specifier that re-declares the same function you had in the base class inside the child class...
For behavior just put mother::func() (mother::dat_set(/*params go here*/) for calling the function with parameters, and I bet you might already know that) to call the respective function...
Note: The override specifier (since C++11) is similar to the virtual specifier, except that it is only usable in dervied classes/structures, and makes the usage of virtual inside child declarations optional (In your base class you have to use virtual instead)...
Edit: You can assign a derived class to a base class but it is not possible to do the opposite, and that is the reason why your code fails... A close attempt to doing something like this would be the usage of namespaces, for example:
namespace some_namespace
{
static std::string dat;
// The child and mother class declarations and other things go here...
}
Kind regards,
Ruks.

c++ Why i need pointer casting each time i request method from container object

i have annoying problem where i need to pointer cast pointer member
here is example
class GlobalInterface
{
public:
virtual void DoAction() = 0;
}
class ActionClass_A: public GlobalInterface
{
public:
ActionClass_A(){};
~ActionClass_A(){};
void DoAction() { ..... } ;
void DoSomeActionOnlyForA() { ..... } ;
}
class ActionClass_B: public GlobalInterface
{
public:
ActionClass_B(){};
~ActionClass_B(){};
void DoAction() { ..... } ;
void DoSomeActionOnlyForB() { ..... } ;
}
#include "GlobalInterface.h"
#include "ActionClass_A.h"
#include "ActionClass_B.h"
class GlobalContainer()
{
public:
GlobalContainer(GlobalInterface* _action)
{
pAction = _action;
}
GlobalInterface* getAction() { return pAction; };
private:
GlobalInterface* pAction;
}
// Main
GlobalContainer* pGlobalContainer = new GlobalContainer(new ActionClass_B());
// WHY i need this casting to get the ActionClass_B DoAction()???
((ActionClass_B*)pGlobalContainer->getAction())->DoSomeActionOnlyForA();
i just want to avoid this casting , and call it like this :
and it will know which implamention it should invoke based on the object type
pGlobalContainer->getAction()->DoSomeActionOnlyForA()
or
pGlobalContainer->getAction()->DoSomeActionOnlyForB()
The virtual function in the base class is private. It should work with a public function.
... and it will know which implamention it should invoke based on the
object type.
But you're not letting it decide what implementation it should invoke based on type, you're trying to make that decision yourself by calling DoSomeActionOnlyForA() or DoSomeActionOnlyForB() directly.
This doesn't work because at the moment of the call the static type of the object is GlobalInterface* and the GlobalInterface class doesn't have member functions named like that.
The way to achieve what you want, let each derived class have it's own behavior, is to understand and use virtual functions correctly. For example you could do this:
class GlobalInterface
{
public:
virtual ~GlobalInterface() {}
virtual void DoAction() = 0;
};
class ActionClass_A: public GlobalInterface
{
public:
ActionClass_A() {}
~ActionClass_A() {}
void DoAction()
{
DoSomeActionOnlyForA(); // call specific action for A
}
void DoSomeActionOnlyForA() { /* implement specific action for A */ } ;
};
class ActionClass_B: public GlobalInterface
{
public:
ActionClass_B() {}
~ActionClass_B() {}
void DoAction()
{
DoSomeActionOnlyForB(); // call specific action for B
}
void DoSomeActionOnlyForB() { /* implement specific action for B */ } ;
};
As you can see, you have a virtual function DoAction() that is overridden in each of the derived classes to call the appropriate functionality for that class.
Then you can use it like this:
GlobalContainer* pGlobalContainer = new GlobalContainer(new ActionClass_B());
pGlobalContainer->getAction()->DoAction();
This will call ActionClass_B::DoAction() which in turn calls ActionClass_B::DoSomeActionOnlyForB().
If you instead create the container like this:
GlobalContainer* pGlobalContainer = new GlobalContainer(new ActionClass_A());
then the same call pGlobalContainer->getAction()->DoAction(); will instead call ActionClass_A::DoAction() which in turn calls the appropriate functionality for A.
As you can see, in this case it does indeed call the appropriate function based on the dynamic type of the object (DoAction() from A or from B).

c++ overriding a function only for a specific instance

I was wondering whether there's a way to override a function for a specific instance only. For ex,
class A
{
public:
...
void update();
...
}
int main()
{
...
A *first_instance = new A();
// I want this to have a specific update() function.
// ex. void update() { functionA(); functionB(); ... }
A *second_instance = new A();
// I want this to have a different update() function than the above one.
// ex. void update() { functionZ(); functionY(); ...}
A *third_instance = new A();
// ....so on.
...
}
Is there a way to achieve this?
I think virtual function is just what you want, with virtual function, different instances of the same type can have different functions, but you need to inherit the base class. for example
class A
{
public:
...
virtual void update()
{
std::cout << "Class A\n";
}
...
};
class B: public A
{
public:
virtual void update()
{
std::cout << "Class B\n";
}
};
class C: public A
{
public:
virtual void update()
{
std::cout << "Class C\n";
}
};
int main()
{
...
A *first_instance = new A();
// I want this to have a specific update() function.
// ex. void update() { functionA(); functionB(); ... }
A *second_instance = new B();
// I want this to have a different update() function than the above one.
// ex. void update() { functionZ(); functionY(); ...}
A *third_instance = new C();
// ....so on.
...
}
each instance in the above code will bind different update functions.
Besides, you can also use function pointer to implement your requirement, but it is not recommended. For example
class A
{
public:
A(void(*u)())
{
this->update = u;
}
...
void (*update)();
};
void a_update()
{
std::cout << "update A\n";
}
void b_update()
{
std::cout << "update B\n";
}
void c_update()
{
std::cout << "update C\n";
}
int main()
{
...
A first_instance(a_update);
// I want this to have a specific update() function.
// ex. void update() { functionA(); functionB(); ... }
A second_instance(b_update);
// I want this to have a different update() function than the above one.
// ex. void update() { functionZ(); functionY(); ...}
A third_instance(c_update);
// ....so on.
...
}
Hope helps!
Hold a function in the class.
#include <iostream>
#include <functional>
using namespace std;
class Foo
{
public:
Foo(const function<void ()>& f) : func(f)
{
}
void callFunc()
{
func();
}
private:
function<void ()> func;
};
void printFoo() { cout<<"foo"<<endl; }
void printBar() { cout<<"bar"<<endl; }
int main()
{
Foo a(printFoo);
Foo b(printBar);
a.callFunc();
b.callFunc();
}
You may have noticed that the end brace of a class is often followed by a semicolon, whereas the end braces of functions, while loops etc don't. There's a reason for this, which relates to a feature of struct in C. Because a class is almost identical to a struct, this feature exists for C++ classes too.
Basically, a struct in C may declare a named instance instead of (or as well as) a named "type" (scare quotes because a struct type in C isn't a valid type name in itself). A C++ class can therefore do the same thing, though AFAIK there may be severe limitations on what else that class can do.
I'm not in a position to check at the moment, and it's certainly not something I remember using, but that may mean you can declare a named class instance inheriting from a base class without giving it a class name. There will still be a derived type, but it will be anonymous.
If valid at all, it should look something like...
class : public baseclass // note - no derived class name
{
public:
virtual funcname ()
{
...
}
} instancename;
Personally, even if this is valid, I'd avoid using it for a number of reasons. For example, the lack of a class name means that it's not possible to define member functions separately. That means that the whole class declaration and definition must go where you want the instance declared - a lot of clutter to drop in the middle of a function, or even in a list of global variables.
With no class name, there's presumably no way to declare a constructor or destructor. And if you have non-default constructors from the base class, AFAIK there's no way to specify constructor parameters with this.
And as I said, I haven't checked this - that syntax may well be illegal as well as ugly.
Some more practical approaches to varying behaviour per-instance include...
Using dependency injection - e.g. providing a function pointer or class instance (or lambda) for some part of the behavior as a constructor parameter.
Using a template class - effectively compile-time dependency injection, with the dependency provided as a function parameter to the template.
I think it will be the best if you'll tell us why do you need to override a function for a specific instance.
But here's another approach: Strategy pattern.
Your class need a member that represent some behaviour. So you're creating some abstract class that will be an interface for different behaviours, then you'll implement different behaviours in subclasses of that abstract class. So you can choose those behaviours for any object at any time.
class A;//forward declaration
class Updater
{
public:
virtual ~Updater() {};//don't forget about virtual destructor, though it's not needed in this case of class containing only one function
virtual void update(A&) = 0;
}
class SomeUpdater
{
public:
virtual void update(A & a);//concrete realisation of an update() method
}
class A
{
private:
Updater mUpdater;
public:
explicit A(Updater updater);//constructor takes an updater, let's pretend we want to choose a behaviour once for a lifetime of an object - at creation
void update()
{
mUpdater.update(this);
}
}
You can use local classes, yet, personally, I consider the "hold function in the class" approach mentioned in the other answer better. I'd recommend the following approach only if doFunc must access internals of your base class, which is not possible from a function held in a member variable:
class ABase {
public:
void Func () { this->doFunc (); }
private:
virtual void doFunc () = 0;
public:
virtual ~ABase () { }
};
ABase* makeFirstA () {
class MyA : public ABase {
virtual void doFunc () { std::cout << "First A"; }
};
return new MyA;
}
ABase* makeSecondA () {
class MyA : public ABase {
virtual void doFunc () { std::cout << "Second A"; }
};
return new MyA;
}
int main () {
std::shared_ptr<ABase> first (makeFirstA ());
std::shared_ptr<ABase> second (makeSecondA ());
first->Func ();
second->Func ();
}
From a design patterns point of view, the "local classes" approach implements the template method pattern, while the "hold a function(al) in a member variable" approach reflects the strategy pattern. Which one is more appropriate depends on what you need to achieve.

C++ private and protected virtual method

It seems that it is good to make the virtual methods private in order to separate the interfaces for following two clients -
1. clients that instantiate an object and call the method
2. clients that derive from the class and may want to override the method.
Simply put - the first client does not need to know if a method is virtual. He will call the base class public non-virtual method which in turn will call the private virtual method. See code below for example.
Now in the case where the virtual method needs to super-message its base class' corresponding virtual method such as say a Save method - which has to pass through all virtual methods in the chain of inheritance in order to save data corresponding to each level of derivation - we have no option but to use a protected virtual method - unless there is a way to guarantee saving of data at all levels of derivation without using super messaging (there is none that I know).
I would like to know if above reasoning correct.
Make sure you use the scroll to see the entire code.
#include <iostream>
using namespace std;
class A {
string data;
protected:
virtual void SaveData()= 0;
public:
A():data("Data of A"){}
void Save(){
cout << data << endl;
SaveData();
}
};
class B : public A {
string data;
protected:
virtual void SaveData() { cout << data << endl;}
public:
B():data("Data of B") {}
};
class C : public B {
string data;
protected:
virtual void SaveData() {
B::SaveData();
cout << data << endl;
}
public:
C():data("Data of C") {}
};
int main(int argc, const char * argv[])
{
C c;
c.Save();
return 0;
}
Yes, if you need to call the SaveData of another class, it needs to be accessible from that class - so public or protected.
You are exactly right:
NVI (Non-Virtual Interface) requires that virtual methods not be public
Calling the base class method requires that it not private
therefore protected is the obvious solution, at least in C++03. Unfortunately it means you have to trust the derived class developer not to forget to call "super".
In C++11, you can use final to prevent a derived class from overriding a virtual method; it means though that you are forced to introduce a new hook, example:
class Base {
public:
void save() {
// do something
this->saveImpl();
// do something
}
private:
virtual void saveImpl() {}
};
class Child: public Base {
private:
virtual void saveImpl() final {
// do something
this->saveImpl2();
// do something
}
virtual void saveImpl2() {}
};
Of course, there is the trouble of having to come up with a new name each and every time... but at least you are guaranteed that Child::saveImpl will be called because none of its children can override it.
It's difficult to tell what you're asking, but from the example, you do not need to make the method protected. It actually can be private. For details about the subtleties see this post: What is the point of a private pure virtual function?.
So long as you're not calling the private member from derived class (or outside classes), you're ok. Overriding of private members is ok. It does sound quite naughty and wrong that you can override your parent's privates, but in c++ you're allowed to do this.
The following should be ok:
#include <iostream>
using namespace std;
class A {
string data;
private:
virtual void SaveData()= 0;
public:
A():data("Data of A"){}
void Save(){
cout << data << endl;
SaveData();
}
};
class B : public A {
string data;
private:
virtual void SaveData() { cout << data << endl;}
public:
B():data("Data of B") {}
};