Click here to Skip to main content
13,792,957 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
#include<iostream>
using namespace std;
class root{
protected:
    int value;
public:
    void setvalue(int a){
        value=a;
    }
};
class first:public root{
public:
    void print(){
    cout<<"I got the value-"<<value<<endl;

    }



};

class second:public root{

public:

    print(){

    cout<<"I got the value-"<<value<<" too"<<endl;

    }

};

int main(){

    root r;

    r.setvalue(44);

    first f;

    second s;

    f.print();

    s.print();

    return 0;



}


What I have tried:

I guess the output should be
"I got the value 44
I got the value 44 too"

But instead of this it is giving me a weird number in the place of 44.
Posted 18-May-18 1:38am
Updated 18-May-18 4:31am
Comments
Richard MacCutchan 18-May-18 7:48am
   
You need to call setvalue on the other objects, they only inherit variable and method definitions from root, not the contents of object r.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

root r;
r.setvalue(44);
Here you create a new object r of type root, and assign a value of 44.

first f;
second s;
Here you create a new object f of type first, which inherits from the class root, but has no relation to the object r. It is not initialised with a value. Same for s.

f.print();
s.print();
Here you display the values of f and s, which are not initialised.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

The second output is non-inialized memory from the second object.

Write a good constructor like
root:root(){value = 0;}//or -1}
root:root(int inValue)

Tip: write "clean code" like class names beginning with a big letter, and clearer output (class name in output).
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.181207.3 | Last Updated 18 May 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100