#include "stdafx.h"
#include<iostream>
using namespace std;



class A
{
public:
	A(){}
	void setdata(int s) {t=s;}
	int getdata(){return t;}
protected:
	int t;
};


class B: public A
{
public:
	B(){}


};


void main()
{
A a;
a.setdata(3);
B b;
cout<<b.getdata();

}

Why I cannot get an output of 3 here? Can anyone help?
Thanks

Recommended Answers

All 8 Replies

a and b are completely separate objects. I think you may have misunderstood the point of inheritance.

since B inherited A,
so in b, we should have t and getdata(),
so I think I am supposed to return t value in the end, which is 3.
Where is the mistake? thanks

Where is the mistake?

The mistake is that you only called setdata(3) on a . b remains default initialized.

I don't find that helpful. As tennis says, b being an object of class B should have inherited the function getdata(0 and the variable t from A, and t has been set at 3 by A's setvalue() function, so it is a mystery to me, too. My textbook has an example that matches exactly, though it doesn't use #include "stdafx.h"

I think what inheritance means here is that B and therefore your b inherit an int t, and the functions setdata() and getdata() which use t, so with a.setdata(3) you give t a value of 3 for the a object, and with b.setdata(4) you can give t a value of 4 for the b object, AND THEN a.getdata() will return 3, b.getdata() will return 4. Hope this helps.

You're confusing classes with objects. Yes, B does indeed inherit t from A . But a and b are separate objects, each with their own copy of t . Thus if you set a's copy of t , b's copy of t does not also get set.

Thanks Narue!
Could you explain a little bit why this code can get an output of 3? thanks

#include "stdafx.h"
#include<iostream>
using namespace std;
class A
{
public:
	A(int s){t=s;}
protected:
	int t;
};
class B: public A
{
public:
         B():A(3){}
	int ret(){return t;}
};

void main()
{
	B b;
         cout<<b.ret()<<endl;
}

B's default constructor calls A's constructor for that object, which sets b's copy of t to 3. Conceptually the chain looks like this:

b.B() -> b.A(3) -> b.t = 3

Note that everything is acting on the object b . This is because under the hood, member functions are passed an object handle. Your code looks more like this to the compiler:

#include <iostream>

using namespace std;

// "Under the hood" transformation of class A
//
struct A {
    int t;
};

void __A$ctor(A *obj, int s)
{
    obj->t = s;
}

// "Under the hood" transformation of class B
//
struct B {
    A __A$sub;
};

void __B$ctor(B *obj)
{
    __A$ctor(&obj->__A$sub, 3);
}

int __B$ret(B *obj)
{
    return obj->__A$sub.t;
}

// "Under the hood" transformation of object usage in main
//
int main()
{
    B b;

    __B$ctor(&b);
    
    cout<< __B$ret(&b) <<endl;
}
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.