0
class A
{
        public:
                int a;
                A() : a(100) { }
               
};

class B : public A
{
        public:
                int b;
                B() : b(200){ }
};

int main()
{
        A a;
        B *ptrB =(B*)&a;

        cout<<ptrB->b<<endl; // Is there a way to get this to print 200??
}

Edited by Nick Evan: Added [CODE] tags

3
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by ahtaniv
0

the pointer is pointing to an object of class A which has no relation with class B...
using base class object cannot print value of b.

0

First use code tags. Your code is not formatted.Formatting makes your code easier to read.

class A
{
public:
     int a;
     A() : a(100) { }
};

class B : public A
{
public:
    int b;
     B() : b(200){ }
};

int main()
{
    A a; (B*)&a;

    cout << ptrB -> b << endl; // Is there a way to get this to print 200??
}

Edited by Mr. K: n/a

0

OK. Thanks for the info. Will have it in mind for future posts.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.