Access to fields of a derived class object, C ++ vs Java

If someone accesses the fields of an object of a derived class after assigning this object to a variable of the type of the base class in java, I get the expected behavior, that is, the print field value of the derived class. In a C ++ value, a field belonging to the base class is printed.

In Java, 6 prints 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 a similar type of behavior in C ++ (print 6).

+4
source share
4 answers

Is it possible to achieve a similar type of behavior in C ++ (print 6).

Of course, this is so if you are doing the same thing as in Java.

, Java , . Java A a = new B(); reference , . ((B)a) .

++ Base b; . - -- . . Java-:

Base& b = p;

Base, Derived&, undefined.

P.S. , , . undefined.

+5

++ b = p; slicing p b, b - Base. static_cast<Derived&>(b) UB.

, b Derived . Derived.

int main ( int argc, char **argv ) {

    Derived p;
    Base& b = p;
    cout << static_cast<Derived&>(b).j << endl;
    return 0;
}

LIVE

+3

, ++ Java-. . , , .

A main()

int main ( int argc, char **argv )
{
    Base *b = new Derived;

    std::cout << ((Derived *)p)->j << endl;
    return 0;
}

() Java-, , Java ++, . , .

std::cout << ((Derived *)p)->j << endl ( ++) std::cout << (*((Derived *)p)).j << endl, , , Java.

main() undefined , .

Derived pcasted = static_cast<Derived&>(b);

b Derived. b Derived, pcasted b, Derived, . undefined.

+2

:

  • -
  • Stack vs heap (reference)
  • ++ - Java.

!

+1

All Articles