How can I simulate interfaces in C++? - c++

Since C++ lacks the interface feature of Java and C#, what is the preferred way to simulate interfaces in C++ classes? My guess would be multiple inheritance of abstract classes.
What are the implications in terms of memory overhead/performance?
Are there any naming conventions for such simulated interfaces, such as SerializableInterface?

Since C++ has multiple inheritance unlike C# and Java, yes you can make a series of abstract classes.
As for convention, it is up to you; however, I like to precede the class names with an I.
class IStringNotifier
{
public:
virtual void sendMessage(std::string &strMessage) = 0;
virtual ~IStringNotifier() { }
};
The performance is nothing to worry about in terms of comparison between C# and Java. Basically you will just have the overhead of having a lookup table for your functions or a vtable just like any sort of inheritance with virtual methods would have given.

There's really no need to 'simulate' anything as it is not that C++ is missing anything that Java can do with interfaces.
From a C++ pointer of view, Java makes an "artificial" disctinction between an interface and a class. An interface is just a class all of whose methods are abstract and which cannot contain any data members.
Java makes this restriction as it does not allow unconstrained multiple inheritance, but it does allow a class to implement multiple interfaces.
In C++, a class is a class and an interface is a class. extends is achieved by public inheritance and implements is also achieved by public inheritance.
Inheriting from multiple non-interface classes can result in extra complications but can be useful in some situations. If you restrict yourself to only inheriting classes from at most one non-interface class and any number of completely abstract classes then you aren't going to encounter any other difficulties than you would have in Java (other C++ / Java differences excepted).
In terms of memory and overhead costs, if you are re-creating a Java style class hierarchy then you have probably already paid the virtual function cost on your classes in any case. Given that you are using different runtime environments anyway, there's not going to be any fundamental difference in overhead between the two in terms of cost of the different inheritance models.

"What are the implications in terms of memory overhead/performance?"
Usually none except those of using virtual calls at all, although nothing much is guaranteed by the standard in terms of performance.
On memory overhead, the "empty base class" optimization explicitly permits the compiler to layout structures such that adding a base class which has no data members does not increase the size of your objects. I think you're unlikely to have to deal with a compiler which does not do this, but I could be wrong.
Adding the first virtual member function to a class usually increases objects by the size of a pointer, compared with if they had no virtual member functions. Adding further virtual member functions makes no additional difference. Adding virtual base classes might make a further difference, but you don't need that for what you're talking about.
Adding multiple base classes with virtual member functions probably means that in effect you only get the empty base class optimisation once, because in a typical implementation the object will need multiple vtable pointers. So if you need multiple interfaces on each class, you may be adding to the size of the objects.
On performance, a virtual function call has a tiny bit more overhead than a non-virtual function call, and more importantly you can assume that it generally (always?) won't be inlined. Adding an empty base class doesn't usually add any code to construction or destruction, because the empty base constructor and destructor can be inlined into the derived class constructor/destructor code.
There are tricks you can use to avoid virtual functions if you want explicit interfaces, but you don't need dynamic polymorphism. However, if you're trying to emulate Java then I assume that's not the case.
Example code:
#include <iostream>
// A is an interface
struct A {
virtual ~A() {};
virtual int a(int) = 0;
};
// B is an interface
struct B {
virtual ~B() {};
virtual int b(int) = 0;
};
// C has no interfaces, but does have a virtual member function
struct C {
~C() {}
int c;
virtual int getc(int) { return c; }
};
// D has one interface
struct D : public A {
~D() {}
int d;
int a(int) { return d; }
};
// E has two interfaces
struct E : public A, public B{
~E() {}
int e;
int a(int) { return e; }
int b(int) { return e; }
};
int main() {
E e; D d; C c;
std::cout << "A : " << sizeof(A) << "\n";
std::cout << "B : " << sizeof(B) << "\n";
std::cout << "C : " << sizeof(C) << "\n";
std::cout << "D : " << sizeof(D) << "\n";
std::cout << "E : " << sizeof(E) << "\n";
}
Output (GCC on a 32bit platform):
A : 4
B : 4
C : 8
D : 8
E : 12

Interfaces in C++ are classes which have only pure virtual functions. E.g. :
class ISerializable
{
public:
virtual ~ISerializable() = 0;
virtual void serialize( stream& target ) = 0;
};
This is not a simulated interface, it is an interface like the ones in Java, but does not carry the drawbacks.
E.g. you can add methods and members without negative consequences :
class ISerializable
{
public:
virtual ~ISerializable() = 0;
virtual void serialize( stream& target ) = 0;
protected:
void serialize_atomic( int i, stream& t );
bool serialized;
};
To the naming conventions ... there are no real naming conventions defined in the C++ language. So choose the one in your environment.
The overhead is 1 static table and in derived classes which did not yet have virtual functions, a pointer to the static table.

In C++ we can go further than the plain behaviour-less interfaces of Java & co.
We can add explicit contracts (as in Design by Contract) with the NVI pattern.
struct Contract1 : noncopyable
{
virtual ~Contract1();
Res f(Param p) {
assert(f_precondition(p) && "C1::f precondition failed");
const Res r = do_f(p);
assert(f_postcondition(p,r) && "C1::f postcondition failed");
return r;
}
private:
virtual Res do_f(Param p) = 0;
};
struct Concrete : virtual Contract1, virtual Contract2
{
...
};

Interfaces in C++ can also occur statically, by documenting the requirements on template type parameters.
Templates pattern match syntax, so you don't have to specify up front that a particular type implements a particular interface, so long as it has the right members. This is in contrast to Java's <? extends Interface> or C#'s where T : IInterface style constraints, which require the substituted type to know about (I)Interface.
A great example of this is the Iterator family, which are implemented by, among other things, pointers.

If you don't use virtual inheritance, the overhead should be no worse than regular inheritance with at least one virtual function. Each abstract class inheritted from will add a pointer to each object.
However, if you do something like the Empty Base Class Optimization, you can minimize that:
struct A
{
void func1() = 0;
};
struct B: A
{
void func2() = 0;
};
struct C: B
{
int i;
};
The size of C will be two words.

By the way MSVC 2008 has __interface keyword.
A Visual C++ interface can be defined as follows:
- Can inherit from zero or more base
interfaces.
- Cannot inherit from a base class.
- Can only contain public, pure virtual
methods.
- Cannot contain constructors,
destructors, or operators.
- Cannot contain static methods.
- Cannot contain data members;
properties are allowed.
This feature is Microsoft Specific. Caution: __interface has no virtual destructor that is required if you delete objects by its interface pointers.

There is no good way to implement an interface the way you're asking. The problem with an approach such as as completely abstract ISerializable base class lies in the way that C++ implements multiple inheritance. Consider the following:
class Base
{
};
class ISerializable
{
public:
virtual string toSerial() = 0;
virtual void fromSerial(const string& s) = 0;
};
class Subclass : public Base, public ISerializable
{
};
void someFunc(fstream& out, const ISerializable& o)
{
out << o.toSerial();
}
Clearly the intent is for the function toSerial() to serialize all of the members of Subclass including those that it inherits from Base class. The problem is that there is no path from ISerializable to Base. You can see this graphically if you execute the following:
void fn(Base& b)
{
cout << (void*)&b << endl;
}
void fn(ISerializable& i)
{
cout << (void*)&i << endl;
}
void someFunc(Subclass& s)
{
fn(s);
fn(s);
}
The value output by the first call is not the same as the value output by the second call. Even though a reference to s is passed in both cases, the compiler adjusts the address passed to match the proper base class type.

Related

Virtual method returning enum that represents type of derived object - is it ok (in terms of design)?

Suppose I have an abstract base class Base. I want the derived classes to be processed in a different way depending on their types. I could do it like this:
class Base {
public:
virtual void process() const = 0;
};
class DerivedOne : public Base {
public:
virtual void process() const { std::cout << "processed one" << std::endl; }
};
But I'd like to move the logic of processing into separate class so that derived classes were not aware of the way they are processed. I have an idea of how to do it, but I am not sure if it is common or elegant:
enum Type {
TypeOne,
TypeTwo
};
class Base {
public:
virtual Type type() const = 0;
};
class DerivedOne : public Base {
public:
virtual Type type() const { return TypeOne; }
};
class DerivedTwo : public Base {
public:
virtual Type type() const { return TypeTwo; }
};
class Processor {
void process(const Base& b) {
switch(b.type()) {
case TypeOne: std::cout << "processed one" << std::endl; break;
case TypeTwo: std::cout << "processed two" << std::endl; break;
}
}
};
So the questions are:
1) is it ok when virtual method returns some constant representing the type of derived class?
2) is such approach of using switch on the type of object commonly used?
3) are there any other design ideas to separate processing from the object being processed?
That makes no sense.
You're taking virtual dispatch, a feature deliberately created to make polymorphism work without messing up your call site or removing ClassX logic from actually within ClassX ... and trying to undo all its usefulness.
You might as well not bother with polymorphism at all, and simply store your Type as a member variable in a single class.
Quiz Time.
Why do we use polymorphism?
To provide different behavior for similar operations, where the behavior is selected at run-time.
Polymorphism is used to abstract away the implementation of an operation from the provision of that operation. All Base objects for example have a common set of methods. How those methods are implemented depends on the object itself. As a user of the object, we don't care what specific kind of object it is -- only that is is derived from Base and therefore has certian methods on it. We just call the method and let the object handle how it's implemented.
Why would we need to determine at run-time which subclass an object is derived from?
Because only the subclass provides some operation we need.
Designing an interface with a pure virtual method that indicates the actual type of object smells. It's smelly because the only reason why you would need to know the actual type of an object is because the interface doesn't provide some functionality we need, and the only thing that does provide that functionality is the object itself. But this is counter to the point of polymorphism -- to ensure the provision of functionality while leaving the details of that functionality up to the object.
Consider using RTTI's typeid() function rather than creating your own virtual method to return the derived type.
<humor> because you are using a built-in C++ function people will be less likely to argue with you about whether your design is broken. If the C++ standards committee thinks you need the functionality then it's probably legit! </humor>

Ambiguity in multiple inheritance of interfaces in C++

I made a test code as following:
#include <iostream>
using namespace std;
#ifndef interface
#define interface struct
#endif
interface Base
{
virtual void funcBase() = 0;
};
interface Derived1 : public Base
{
virtual void funcDerived1() = 0;
};
interface Derived2 : public Base
{
virtual void funcDerived2() = 0;
};
interface DDerived : public Derived1, public Derived2
{
virtual void funcDDerived() = 0;
};
class Implementation : public DDerived
{
public:
void funcBase() { cout << "base" << endl; }
void funcDerived1() { cout << "derived1" << endl; }
void funcDerived2() { cout << "derived2" << endl; }
void funcDDerived() { cout << "dderived" << endl; }
};
int main()
{
DDerived *pObject = new Implementation;
pObject->funcBase();
return 0;
}
The reason I wrote this code is to test if the function funcBase() can be called in an instance of DDerived or not. My C++ complier (Visual Studio 2010) gave me a compile error message when I tried to compile this code. In my opinion, there is no problem in this code because it is certain that the function funcBase() will be implemented (thus overriden) in some derived class of the interface DDerived, because it is pure virtual. In other words, any pointer variable of type Implementation * should be associated with an instance of a class deriving Implentation and overriding the function funcBase().
My question is, why the compiler give me such an error message? Why the C++ syntax is defined like that; i.e., to treat this case as an error? How can I make the code runs? I want to allow multiple inheritance of interfaces. Of course, if I use "virtual public" or re-declare the function funcBase() in Implementation like
interface DDerived : public Derived1, public Derived2
{
virtual void funcBase() = 0;
virtual void funcDDerived() = 0;
};
then everything runs with no problem.
But I don't want to do that and looking for more convenient method, because virtual inheritance may degrade the performance, and re-declaration is so tedious to do if inheritance relations of classes are very complex. Is there any methods to enable multiple inheritance of interfaces in C++ other than using virtual inheritance?
As you've defined it, your object structure looks like this:
The important point here is that each instance of Implementation contains two entirely separate instances of Base. You're providing an override of Base::funcBase, but it doesn't know whether you're trying to override funcBase for the Base you inherited through Derived1, or the Base you inherited through Derived2.
Yes, the clean way to deal with this is virtual inheritance. This will change your structure so there's only one instance of Base:
This is almost undoubtedly what you really want. Yes, it got a reputation for performance problems in the days of primitive compilers and 25 MHz 486's and such. With a modern compiler and processor, you're unlikely to encounter a problem.
Another possibility would be some sort of template-based alternative, but that tends to pervade the rest of your code -- i.e., instead of passing a Base *, you write a template that will work with anything that provides functions A, B, and C, then pass (the equivalent of) Implementation as a template parameter.
The C++ language is designed in such a way that in your first approach without virtual inheritance there will be two parent copies of the method and it can't figure out which one to call.
Virtual inheritance is the C++ solution to inheriting the same function from multiple bases, so I would suggest just using that approach.
Alternately have you considered just not inheriting the same function from multiple bases? Do you really have a derived class that you need to be able to treat as Derived1 or Derived2 OR Base depending on the context?
In this case elaborating on a concrete problem rather than a contrived example may help provide a better design.
DDerived *pObject = new Implementation;
pObject->funcBase();
This creates a pointer of type DDerived to a Implementation. When you are using DDerived you really just have a pointer to an interface.
DDerived does not know about the implementation of funcBase because of the ambiguity of having funcBase being defined in both Derived1 and Derived2.
This has created a inheritance diamond which is what is really causing the problem.
http://en.wikipedia.org/wiki/Diamond_problem
I also had to check on the interface "keyword" you have in there
it's an ms-specific extension that's recognised by visual studio
I think C++ Standard 10.1.4 - 10.1.5 can help you to understand the problem in your code.
class L { public: int next; /∗ ... ∗/ };
class A : public L { /∗...∗/ };
class B : public L { /∗...∗/ };
class C : public A, public B { void f(); /∗ ... ∗/ };
10.1.4 A base class specifier that does not contain the keyword virtual,
specifies a non-virtual base class. A base class specifier that
contains the keyword virtual, specifies a virtual base class. For each
distinct occurrence of a non-virtual base class in the class lattice
of the most derived class, the most derived object (1.8) shall contain
a corresponding distinct base class subobject of that type. For each
distinct base class that is specified virtual, the most derived object
shall contain a single base class subobject of that type. [ Example:
for an object of class type C, each distinct occurrence of a
(non-virtual) base class L in the class lattice of C corresponds
one-to-one with a distinct L subobject within the object of type C.
Given the class C defined above, an object of class C will have two
subobjects of class L as shown below.
10.1.5 In such lattices, explicit qualification can be used to specify which
subobject is meant. The body of function C::f could refer to the
member next of each L subobject: void C::f() { A::next = B::next; } //
well-formed. Without the A:: or B:: qualifiers, the definition of C::f
above would be ill-formed because of ambiguity
So just add qualifiers when calling pObject->funcBase() or solve ambiguity in another way.
pObject->Derived1::funcBase();
Updated: Also very helpful reading will be 10.3 Virtual Functions of Standard.
Have a nice weekend :)

Multiple Inheritance : size of class for virtual pointers?

Given the code:
class A{};
class B : public virtual A{};
class C : public virtual A{};
class D : public B,public C{};
int main(){
cout<<"sizeof(D)"<<sizeof(D);
return 0;
}
Output:
sizeof(D) 8
Every class contains its own virtual pointer only not of any of its base class,
So, why the Size of class(D) is 8?
It depends on compiler implementation. My compiler is Visual Stdio C++ 2005.
Code like this:
int main(){
cout<<"sizeof(B):"<<sizeof(B) << endl;
cout<<"sizeof(C):"<<sizeof(C) << endl;
cout<<"sizeof(D):"<<sizeof(D) << endl;
return 0;
}
It will output
sizeof(B):4
sizeof(C):4
sizeof(D):8
class B has only one virtual pointer. So sizeof(B)=4. And class C is also.
But D multiple inheritance the class B and class C. The compile don't merge the two virtual table.So class D has two virtual pointer point to each virtual table.
If D only inheritance one class and not virtual inheritance. It will merge they virtual table.
It depends on compiler implementation so you should specify which compiler you're using. Anyway D derives from two classes so it contains pointers to B and C vtables base class pointers (I don't know a good name for this).
To test this you may declare a pointer to B and a pointer to C and cast the address of D to base class pointer. Dump that values and you'll see they're different!
EDIT
Test made with Visual C++ 10.0, 32 bit.
class Base
{
};
class Derived1 : public virtual Base
{
};
class Derived2 : public virtual Base
{
};
class Derived3 : public virtual Base
{
};
class ReallyDerived1 : public Derived1, public Derived2, public Derived3
{
};
class ReallyDerived2 : public Derived1, public Derived2
{
};
class ReallyDerived3 : public Derived2
{
};
void _tmain(int argc, _TCHAR* argv[])
{
std::cout << "Base: " << sizeof(Base) << std::endl;
std::cout << "Derived1: " << sizeof(Derived1) << std::endl;
std::cout << "ReallyDerived1: " << sizeof(ReallyDerived1) << std::endl;
std::cout << "ReallyDerived2: " << sizeof(ReallyDerived2) << std::endl;
std::cout << "ReallyDerived3: " << sizeof(ReallyDerived3) << std::endl;
}
Output, guess, is not surprising:
Base: 1 byte (OK, this is a surprise, at least for me).
Derived1: 4 bytes
ReallyDerived1: 12 bytes (4 bytes per base class because of multiple inheritance)
ReallyDerived2: 8 bytes (as guessed)
ReallyDerived3: 4 bytes (just one base class with virtual inheritance in the path but this is non virtual).
Adding a virtual method to the base you get 4 bytes more for each class. So probably extra bytes aren't vtable pointers but base class pointers used in multiple inheritance, this behavior does not change removing virtual inheritance (but if not virtual the size doesn't change adding more bases).
First: without virtual functions, it's probable that there isn't a
vptr at all in the classes. The 8 bytes you're seeing are an artifact
of the way virtual inheritance is implemented.
It's often possible for several classes in a hierarchy to share the same
vptr. For this to occur, it is necessary for their offset in the
final class to be the same, and for the list of vtable entries in the
base class to be an initial sequence the list of vtable entries in the
derived class.
Both conditions are met in almost all implementations for single
inheritance. No matter how deep the inheritance, there will usually be
only one vptr, shared between all of the classes.
In the case of multiple inheritance, there will always be at least one
class for which these requirements aren't met, since the two base
classes can't have a common start address, and unless they have exactly
the same virtual functions, only one's vtable could possibly be an
initial sequence of the other.
Virtual inheritance adds another quirk, since the position of the
virtual base relative to the class inheriting from it will vary
depending on the rest of the hierarchy. Most implementations I've seen
use a separate pointer for this, although it should be possible to put
this information in the vtable as well.
If we take your hierarchy, adding virtual functions so that we are
certain of having a vptr, we notice that B and D can still share a
vtable, but both A and C need separate vtables. This means that
if your classes had virtual functions, you would need at least three
vptr. (From this I conclude that your implementation is using
separate pointers to the virtual base. With B and D sharing the
same pointer, and C with its own pointer. And of course, A doesn't
have a virtual base, and doesn't need a pointer to itself.)
If you're trying to analyse exactly what is going on, I'd suggest adding
a new virtual function in each class, and adding a pointer sized
integral type that you initial with a different known value for each
class. (Use constructors to set the value.) Then create an instance of
the class, take it's address, then output the address for each base
class. And then dump the class: the known fixed values will help in
identifying where the different elements lie. Something like:
struct VB
{
int vb;
VB() : vb( 1 ) {}
virtual ~VB() {}
virtual void fvb() {}
};
struct Left : virtual VB
{
int left;
Left() : left( 2 ) {}
virtual ~Left() {}
virtual void fvb() {}
virtual void fleft() {}
};
struct Right : virtual VB
{
int right;
Right() : right( 3 ) {}
virtual ~Right() {}
virtual void fvb() {}
virtual void fright() {}
};
struct Derived : Left, Right
{
int derived;
Derived() : derived( 5 ) {}
virtual ~Derived() {}
virtual void fvb() {}
virtual void fleft() {}
virtual void fright() {}
virtual void fderived() {}
};
You might want to add a Derived2, which derives from Derived and see
what happens to the relative addresses between e.g. Left and VB
depending on whether the object has type Derived or Derived2.
You are making far too many assumptions. This is highly dependent on the ABI, so you should look into the documentation for your platform (my guess is that you are running on a 32bit platform).
The first thing is that there are no virtual functions in your example, and that means that none of the types actually contains a pointer to the virtual table. So where did those 2 pointers come from? (I am assuming you are on a 32bit architecture). Well, virtual inheritance is the answer. When you inherit virtually, the relative location of the virtual base (A) with respect to the extra elements in the derived type (B,C) will change along the inheritance chain. In the case of a B or C object the compiler can lay the types as [A,B'] and [A,C'] (where X' is the extra fields of X not present in A).
Now virtual inheritance means that there will only be one A subobject in the case of D, so the compiler can layout the D type as [A,B',C',D] or [A,C',B',D] (or any other combination, A might be at the end of the object, etc, this is defined in the ABI). So what does this imply, this implies that member functions of B and C cannot assume where the A subobject might be (in the event of non-virtual inheritance, the relative location is known), because the complete type might actually be some other type down the chain.
The solution to the problem is that both B and C usually contain an extra pointer-to-base pointer, similar but not equivalent to the virtual pointer. In the same way that the vptr is used to dynamically dispatch to a function, this extra pointer is used to dynamically find the base.
If you are interested in all this details, I recommend that you read the Itanium ABI, which is widely used not only in Itanium but also in other Intel 64 architectures (and a modified version in 32 architectures) by different compilers.

Correct way to inherit from a virtual class with non-virtual parent

I've written this test code that uses three types: struct One is a normal type with no virtual members, struct Two : One has a pure virtual function and a virtual destructor, and struct Three : Two implements Two's interface.
#include <iostream>
struct One
{
~One() {
std::cout << "~One()\n";
}
};
struct Two : One
{
virtual ~Two() {
std::cout << "~Two()\n";
}
virtual void test() = 0;
};
struct Three : Two
{
virtual ~Three() {
std::cout << "~Three()\n";
}
virtual void test() {
std::cout << "Three::test()\n";
}
};
int main()
{
Two* two = new Three;
two->test();
One* one = two;
delete one;
}
Unsurprisingly, the output was this:
Three::test()
~One()
Is there any way to fix this other than making every destructor virtual? Or should programmers just be careful not to run into this situation? I find it odd that there's no warning when compiling this.
The only "fix" is not to delete the objects through a pointer to One.
If this is a frequent problem, or not, depends on how your classes are used. For example, the standard library contains structs like unary_function without a virtual destructor, but we hardly ever see it misused like this.
delete one invokes undefined behaviour, because the dynamic type of the object does not match the static type, and the static type does not have a virtual destructor.
The usual way to avoid problems like this is to make destructors be either public and virtual, or protected and non-virtual (on classes that are expected to be used in this way).
You must be careful and make One's destructor virtual. Some compilers do warn about this.
If you want working destructors in derived classes then you must define them as virtual. It is the only way.

Why doesn't C++ have virtual variables?

This might have been asked a million times before or might be incredibly stupid but why is it not implemented?
class A
{
public:
A(){ a = 5;}
int a;
};
class B:public A
{
public:
B(){ a = 0.5;}
float a;
};
int main()
{
A * a = new B();
cout<<a->a;
getch();
return 0;
}
This code will access A::a. How do I access B::a?
To access B::a:
cout << static_cast<B*>(a)->a;
To explicitly access both A::a and B::a:
cout << static_cast<B*>(a)->A::a;
cout << static_cast<B*>(a)->B::a;
(dynamic_cast is sometimes better than static_cast, but it can't be used here because A and B are not polymorphic.)
As to why C++ doesn't have virtual variables: Virtual functions permit polymorphism; in other words, they let a classes of two different types be treated the same by calling code, with any differences in the internal behavior of those two classes being encapsulated within the virtual functions.
Virtual member variables wouldn't really make sense; there's no behavior to encapsulate with simply accessing a variable.
Also keep in mind that C++ is statically typed. Virtual functions let you change behavior at runtime; your example code is trying to change not only behavior but data types at runtime (A::a is int, B::a is float), and C++ doesn't work that way. If you need to accommodate different data types at runtime, you need to encapsulate those differences within virtual functions that hide the differences in data types. For example (demo code only; for real code, you'd overload operator<< instead):
class A
{
public:
A(){ a = 5;}
int a;
virtual void output_to(ostream& o) const { o << a; }
};
class B:public A
{
public:
B(){ a = 0.5;}
float a;
void output_to(ostream& o) const { o << a; }
};
Also keep in mind that making member variables public like this can break encapsulation and is generally frowned upon.
By not making data public, and accessing them through virtual functions.
Consider for a moment, how what you ask for would have to be implemented. Basically, it would force any access to any data member to go through a virtual function. Remember, you are accessing data through a pointer to an A object, and class A doesn't know what you've done in class B.
In other words, we could make accessing any data member anywhere much slower -- or you could write a virtual method. Guess which C++'s designers chose..
You can't do this and C++ does not support it because it breaks with fundamental C++ principles.
A float is a different type than an int, and name lookup as well as determining what conversions will be needed for a value assignment happens at compile time. However what is really named by a->a including its actual type would only be known at runtime.
You can use templates to parameterize class A
template<typename T>
class A
{
public:
// see also constructor initializer lists
A(T t){ a = t; }
T a;
};
Then you can pass the type, however only at compile time for the above mentioned principle's reason.
A<int> a(5);
A<float> b(5.5f);
(dynamic_cast<B*>(a))->a ?
Why do you need that after all? Are virtual functions not enought?
You can downcast your variable to access B::a.
Something like:
((B*)a)->a
I think it is the same in most OO programming languages. I can't think of any one implementing virtual variables concept...
You can create such effect like this:
#include <iostream>
class A {
public:
double value;
A() {}
virtual ~A() {}
virtual void doSomething() {}
};
class B : public A {
public:
void doSomething() {
A::value = 3.14;
}
};
int main() {
A* a = new B();
a->doSomething();
std::cout << a->value << std::endl;
delete a;
return 0;
}
In the example above you could say that the value of A has the same effect as a virtual variable should have.
Edit: This is the actual answer to your question, but seeing your code example I noticed that you're seeking for different types in the virtual variable. You could replace double value with an union like this:
union {
int intValue;
float floatValue;
} value
and acces it like:
a->value.intValue = 3;
assert(a->value.floatValue == 3);
Note, for speed reasons I would avoid this.
Because according to the C standard, the offset of a field within a class or struct is required to be a compile-time constant. This also applies to when accessing base class fields.
Your example wouldn't work with virtual getters either, as the override requires the same type signature. If that was necessary, your virtual getter would have to return at algebraic type and the receiving code would have to check at run-time if it was of the expected type.
Leaving aside the argument that virtual methods should be private, virtual methods are intended as an extra layer of encapsulation (encapsulating variations in behavior). Directly accessing fields goes against encapsulation to begin with so it would be a bit hypocritical to make virtual fields. And since fields don't define behavior they merely store data, there isn't really any behavior to be virtualized. The very fact that you have a public int or float is an anti-pattern.
This isn't supported by C++ because it violates the principles of encapsulation.
Your classes should expose and implement a public (possibly virtual) interface that tells class users nothing about the internal workings of your class. The interface should describe operations (and results) that the class can do at an abstract level, not as "set this variable to X".