If one accesses the fields of derived class object after assignment this object to variable of base class type in java, i get the expected behaviour, meaning print field's value of the derived class . In c++ value of the field, belonging to the base class is printed.
In Java, 6 is printed as expected:
class Ideone
{
static class A {
static int a = 7;
}
static class B extends A {
static int b = 6;
}
public static void main (String[] args) throws java.lang.Exception
{
A a = new B();
System.out.println(((B)a).b);
}
}
In C++, 7 is printed:
#include <iostream>
using namespace std;
class Base {
int i = 7;
public:
Base(){
std::cout << "Constructor base" << std::endl;
}
~Base(){
std::cout << "Destructor base" << std::endl;
}
Base& operator=(const Base& a){
std::cout << "Assignment base" << std::endl;
}
};
class Derived : public Base{
public:
int j = 6;
};
int main ( int argc, char **argv ) {
Base b;
Derived p;
cout << p.j << endl;
b = p;
Derived pcasted = static_cast<Derived&>(b);
cout << pcasted.j << endl;
return 0;
}
Is it possible to achieve in c++ similar type of behaviour (printing 6).