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??
}

Dani AI

Generated

Short answer: no — forcing the address of an A object into a B* and then reading b is undefined behavior. As pointed out, the pointer in your original post refers to an object whose dynamic type is A, not B, so there is no b member storage to read; reading it can return garbage or crash. was right to remind about formatting, but the root problem is a misuse of downcasting.

Why this is wrong and what to do instead:

  • The C++ object model requires that a pointer-to-derived be used only when the object really is that derived type. Casting a base object’s address to a derived pointer does not create derived data.
  • To do a safe downcast at runtime, make the base polymorphic (one virtual function or a virtual destructor) and use dynamic_cast. That checks the actual type and returns nullptr if the object is not a Derived.
  • If you know an object is actually the derived type (because you created it as such), static_cast is faster but has no runtime check. Avoid C-style casts or reinterpret_cast for this — they don’t make an invalid cast safe.

Example (safe pattern using RTTI):

#include <iostream>

struct Base { virtual ~Base() = default; int a = 100; };
struct Derived : Base { int b = 200; };

int main() {
    Derived d;
    Base* pb = &d;                        // actually points to a Derived
    if (Derived* pd = dynamic_cast<Derived*>(pb))
        std::cout << pd->b << '\n';      // prints 200
}

Practical tips:

  • If you only ever need to call behavior, prefer a virtual method on Base and override it in Derived — no casts needed.
  • Watch out for object slicing (assigning a Derived to a Base by value loses Derived members).
  • If you see strange values after a cast, assume undefined behavior and rework to use real Derived objects, polymorphism, or a variant/visitor pattern.

Recommended Answers

All 3 Replies

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.

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??
}

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.