Can we have a static virtual functions? If not, then WHY? [duplicate] - c++

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C++ static virtual members?
Can we have a static virtual functions? If not, then WHY?
class X
{
public:
virtual static void fun(){} // Why we cant have static virtual function in C++?
};

No, because it doesn't make any sense in C++.
Virtual functions are invoked when you have a pointer/reference to an instance of a class. Static functions aren't tied to a particular instance, they're tied to a class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function virtually.

That would make no sense. The point of virtual member functions is that they are dispatched based on the dynamic type of the object instance on which they are called. On the other hand, static functions are not related to any instances and are rather a property of the class. Thus it makes no sense for them to be virtual. If you must, you can use a non-static dispatcher:
struct Base
{
static void foo(Base & b) { /*...*/ }
virtual ~Base() { }
virtual void call_static() { foo(*this); /* or whatever */ }
};
struct Derived : Base
{
static void bar(int a, bool b) { /* ... */ }
virtual void call_static() { bar(12, false); }
};
Usage:
Base & b = get_instance();
b.call_static(); // dispatched dynamically
// Normal use of statics:
Base::foo(b);
Derived::bar(-8, true);

Related

Whats the usage of private virtual methods? [duplicate]

This question already has answers here:
Private virtual method in C++
(5 answers)
Closed 2 years ago.
considering below example
#include <iostream>
#include <string>
class A
{
public:
virtual void foo() { std::cout<< "FOO A\n"; }
private:
void bar() { std::cout<< "BAR A\n"; }
virtual void vbar() { std::cout<< "VBAR A\n"; }
};
class B : public A
{
public:
void foo() { std::cout<< "FOO B\n"; bar(); vbar(); }
private:
void bar() { std::cout<< "BAR B\n"; }
virtual void vbar() { std::cout<< "VBAR B\n"; }
};
int main()
{
A* b = new B();
b->foo();
}
The output will give us
FOO B
BAR B
VBAR B
Since its simple example first that come to my mind I cant figure out any private virtual method use case. In case of public virtual method, the base pointer class interface will adapt to its defined vtable, but as in given example for private virtuals it doesnt matter
One possible use is for letting a base class define a structure, and having derived classes implement the behaivour of the components of said structure (the template method pattern). For example,
struct foo
{
void do_stuff() {
// defines order in which some operations are executed
do_op1();
do_op1();
do_op3();
}
private:
// These don't have to be pure virtual. A base,
// default implementation could also be provided.
virtual void do_op1() = 0;
virtual void do_op2() = 0;
virtual void do_op3() = 0;
};
// implements the operations
struct foo1 : foo
{
private:
void do_op1() override { ... }
void do_op2() override { ... }
void do_op3() override { ... }
};
The virtual methods are private because it does not make sense to call them in isolation. The base class knows when and how to call them.
There are probably simpler and better ways of implementing this in "modern C++", but this kind of thing might have been seen in the 90s and 00s.
There are situations where it might be useful, some argue, that it should be the prefered method, when possible, like Herb Sutter:
Guideline #2: Prefer to make virtual functions private.
...This lets the derived classes override the function to customize the behavior as needed, without further exposing the virtual functions directly by making them callable by derived classes (as would be possible if the functions were just protected). The point is that virtual functions exist to allow customization; unless they also need to be invoked directly from within derived classes' code, there's no need to ever make them anything but private. But sometimes we do need to invoke the base versions of virtual functions (see the article "Virtually Yours"[5] for an example), and in that case only it makes sense to make those virtual functions protected, thus:
Guideline #3: Only if derived classes need to invoke the base implementation of a virtual function, make the virtual function protected...
http://www.gotw.ca/publications/mill18.htm

Why virtual functions defy access specifiers ? C++ [duplicate]

This question already has answers here:
Public virtual function derived private in C++
(3 answers)
Closed 6 years ago.
let's assume u have a class base and class A which inherits from base . base have a declaration of a pure virtual functions called getValue() which is public , and A contains the definition(implementation) of the functions which is set as private .
When trying to use the function getValue() from base reference or pointer (base& /base*) to an A object it access it even though it's declared as private
Because in C++, virtuality and access are orthogonal concerns. When the compiler sees a base* or base& and it needs to call getValue on it, then it's sufficient that the function is accessible in base.
The fact that A declares its (overriding) getValue as private is irrelevant. After all, how could it be relevant? When base.getValue() or base->getValue() is called, you don't know that you might be dealing with an A. That's the whole point of object-oriented programming in the first place!
This does not mean that it's good style to vary access specifiers within a class hierarchy, though, because it can be confusing. In fact, you should split your getValue into two different functions, one being virtual and the other one non-virtual.
Long story: C++ behaves very different from other popular programming languages here, because it actually allows and encourages private virtual functions. Virtual member functions should be private by default, and public member functions should be non-virtual by default, and call the private virtual ones if necessary. (The only exception is the destructor, of course.) Herb Sutter once called this the Non-Virtual Interface Idiom.
Example:
#include <iostream>
class Base
{
public:
virtual ~Base() {}
int getValue() const
{
int const value = doGetValue();
if (value < 0)
{
// error
}
return value;
}
private:
virtual int doGetValue() const = 0;
};
class A : public Base
{
private:
int doGetValue() const override
{
return 123;
}
};
int main()
{
Base* ptr = new A; // use std::unique_ptr in real code
std::cout << ptr->getValue() << "\n";
delete ptr;
}

Why use virtual function instead of regular? [duplicate]

This question already has answers here:
Why do we need virtual functions in C++?
(27 answers)
Closed 6 years ago.
In c++, the virtual function in base class can be overridden in derived class.
and a member function where the specific implementation will depend on the type of the object it is called upon, at run-time.
Since virtual function has to be implemented(except for pure virtual)
Can I use regular function in base class and redefine it in derived class?
if yes.
What's the point of using virtual function?
Thanks
You can redefine it but it won't work in a polymorphic way.
so if I have a
class base
{
int foo(){ return 3; }
};
class Der : public base
{
int foo() {return 5;}
};
and then have a function that takes a base
void dostuff(base &b)
{
b.foo(); // This will call base.foo and return 3 no matter what
}
and I call it like this
Der D;
dostuff(D);
Now if I change the base to
class base
{
virtual int foo(){ return 3; }
};
void dostuff(base &b)
{
b.foo(); // This will call the most derived version of foo
//which in this case will return 5
}
so the real answer is if you want to write common code that will call the correct function from the base it needs to be virtual.
Actually, Virtual function is base of object oriented language.
In java, all functions are virtual function.
But in c++, virtual function is slower than regular function.
So if there is no need to function override, you should use regular function instead of virtual function.

Virtual function call in constructor [duplicate]

This question already has answers here:
C++ virtual function from constructor [duplicate]
(7 answers)
Closed 9 years ago.
I have this layout
class Base {
public:
virtual void Initialize() { // base Implementation }
Base() { Initialize(); }
};
class der_1 : public Base
{
public:
der_1() : Base() {}
virtual void Initialize() { // der_1 Implementation }
};
class der_2 : public Base
{
public:
der_2() : Base() {}
virtual void Initialize() { // der_2 Implementation }
};
Now, whenever I create a new object of class der_1 or der_2, I will end up calling the base implementation of Initialize(). Apparently, I can't call a virtual function while the object is being created.
As of now, I am calling the Initialize function after I create the object of type der_1 or der_2, which doesn't seem a correct practice to me as that will couple the Initialize function call to each time an object is created.
Can someone suggest me better alternatives?
During the constructor call, the object "is" still only an instance of the base class, so it does know about your overloaded Initialize() function.
There are some suggestions for dealing with the situation here:
C++ virtual function from constructor

Static Virtual functions in c++

I have a base class and a derived one and I want to change base functions while keeping them static as they should be passed to other functions as static.
How can I do that?
The ATL framework gets around the limitation of no virtual statics by making the base class be a template, and then having derived classes pass their class type as a template parameter. The base class can then call derived class statics when needed, eg:
template< class DerivedType >
class Base
{
public:
static void DoSomething() { DerivedType::DoSomethingElse(); }
};
class Derived1 : public Base<Derived1>
{
public:
static void DoSomethingElse() { ... }
};
class Derived2 : public Base<Derived2>
{
public:
static void DoSomethingElse() { ... }
};
This is known as Curiously recurring template pattern, which can be used to implement static polymorphism.
Do you mean you need a pointer to a static function (e.g. to pass as an argument to another function that requires a pointer to a static function), but you need to access that function pointer virtually? In that case, use a virtual function to get the function pointer:
typedef void (*function)();
void do_stuff_with_function(function);
struct Base {
virtual ~Base() {}
virtual function get_function() = 0;
};
struct Derived : Base {
function get_function() {return my_function;}
static void my_function();
};
Derived d;
do_stuff_with_function(d.get_function());
static function can not be virtual since they do not have an instance through which they are accessed. I do believe you can overwrite them though.
You can't have static virtual functions in C++.
Virtual functions typically rely on this pointer to determine the type of function to be called at run time.
A static member function does not pass a this so static virtual functions are not allowed in C++.
If i am correct in understanding ur question, then u can follow the following approach otherwise ignore..
have static function pointer in the base class.
in base class have a static function ( in which u call the function by using that static function pointer)..
in derived classes set that static function poiter to the function defination u wish to execute.. ( in base class u can set the function pointer to some default function).
You cannot have static virtual functions, because it doesn't make sense to have them.