Reputation: 43
#include<iostream>
class A {
int a, b;
public:
void setdata(int x, int y) { a = x; b = y; }
void showdata() { std::cout << a << b; }
};
class B : public A { };
int main() {
A a1;
B b1;
a1.setdata(5, 4);
a1.showdata();
b1.showdata();
}
I just want to print the values of the a
and b
members using the b1
object of class B
, as it can access the member functions of class A
since class B
has public inheritance of class A
. But, I am getting garbage values when I try to print the values of a
and b
using b1
.
Can someone explain why this is happening and how to fix it?
Upvotes: 1
Views: 53
Reputation: 596116
a1
and b1
are completely separate object instances in memory. They have their own copies of the a
and b
members in memory. They have nothing to do with each other at all. Whatever you do to a1
does not affect b1
at all, and vice versa.
You are initializing the members of a1
only, you are not initializing the members of b1
at all. That is why you are seeing garbage when you try to print out the members of b1
.
Before calling b1.showdata()
, you need to call b1.setdata()
to initialize b1
's members, eg:
int main() {
A a1;
B b1;
a1.setdata(5, 4);
a1.showdata();
b1.setdata(1, 2); // <-- add this!
b1.showdata();
}
You should also give class A
a default constructor that initializes the members to default values, in case setdata()
is not called after construction (such as what happened in your case), eg:
class A {
int a, b;
public:
A() : a(0), b(0) {} // <-- add this!
void setdata(int x, int y) { a = x; b = y; }
void showdata() { std::cout << a << b; }
};
Alternatively, you might consider giving class A
and class B
a constructor that takes values as input, eg:
class A {
int a, b;
public:
A() : a(0), b(0) {}
A(int x, int y) : a(x), b(y) {} // <-- add this!
void setdata(int x, int y) { a = x; b = y; }
void showdata() { std::cout << a << b; }
};
class B : public A {
public:
B() : A() {}
B(int x, int y) : A(x, y) {}
};
/* or simpler:
class B : public A {
public:
using A::A; // <-- inherit all constructors
};
*/
int main() {
A a1(5, 4);
B b1(1, 2);
a1.showdata();
b1.showdata();
}
Upvotes: 3