objects

in the main function we are calling a 2 argument constructor,which in turn calls the bixbase constructor with the given parameters in the derived class object,so according to me the output of the program should be 200,but to my disappointment it is 100,plz explain!thnx in advance!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream.h> 
class BixBase
{
    int x, y; 
    public:
    BixBase(int xx = 10, int yy = 10)
    {
        x = xx;
        y = yy;
    }
    void Show()
    {
        cout<< x * y << endl;
    }
};
class BixDerived : public BixBase
{
    private:
        BixBase objBase; 
    public:
    BixDerived(int xx, int yy) : BixBase(xx, yy)
    {
        objBase.Show();
    }
};
int main()
{
    BixDerived objDev(10, 20);
    return 0; 
}
Your derived class should be
1
2
3
4
5
class BixDerived : public BixBase
{
    public:
        BixDerived ( int xx, int yy ) : BixBase ( xx, yy ) { }
};



You were creating two instances of your class item. One correctly, and one in the private section of your derived class that used the default constructor from your base class. You then called Show on the object that had been default constructed.
Last edited on
but wat difference is it making,my concepts r not clear regarding this
What is happening is that when you derive from a class, it is as if it is that class with some more added on top. This means that when you pass 10 and 20 to the constructor, it sets its own x and y values to be 10 and 20, respectively. However, objBase is another, different object, which is being default constructed with 10 and 10 instead.

Your code should be something like this, instead:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include<iostream> 

class BixBase {
    private:
        int x, y; 
    public:
        BixBase(int xx = 10, int yy = 10) {
            x = xx;
            y = yy;
        }

        void Show() {
            std::cout<< x * y << std::endl;
        }
};

class BixDerived : public BixBase {
    public:
        BixDerived(int xx, int yy) : BixBase(xx, yy) {
            Show(); // or, verbose: this->Show();
        }
};

int main() {
    BixDerived objDev(10, 20);
    return 0; 
}
200
Last edited on
Topic archived. No new replies allowed.