Class Drived class

Why in the last 2 lines computers::getPrice() values are 500.7 (set by constructor) and not the price value 100.5 that I get from comp.getPrice()?

#include<string>
using namespace std;

class computers
{

protected:
int noOfDisks;
int noOfCPUs;
float price;

public:
void compSpects(int, int, float);
void showResults();
float getPrice();

computers();
~computers();
};

class servers: public computers
{
public:

servers(){};

string mNo;
void printSpects(int,int,int);
void setMemInfo(int);
float totalMemoryPrice();

private:
int NoOfMemory;
//float memoryPrice;

};
main()
{
computers comp;
comp.showResults(); // results based on constructor settings
comp.compSpects(3,2,100.5);
cout << "results based on setting"<<endl;
cout << " getprice is "<< comp.getPrice()<< endl;
comp.showResults(); // results based on compSpects settig

servers inhComp;
inhComp.mNo = " TI1263S15";
inhComp.setMemInfo(23);
cout<< " total memory price is" << inhComp.totalMemoryPrice()<< endl;



return 0;
}
computers::computers()
{
price=0.;
noOfCPUs=0;
noOfDisks=0;

}
computers::~computers()
{
}

void computers::compSpects(int a, int b, float c)
{
noOfDisks= a;
noOfCPUs= b;
price= c;
}

float computers::getPrice()
{
return price;
}

void computers::showResults()
{
cout<< " Server has " << noOfDisks << " disks"<< "\n";
cout<< " Server has " << noOfCPUs << " CPUs"<< "\n";
cout<< " Server price is " << price<< endl;

}

void servers::setMemInfo( int M_Num)
{
NoOfMemory= M_Num;
}
float servers::totalMemoryPrice()
{
cout<<NoOfMemory<<"computers price "<<computers::getPrice()<< endl;

return (float)NoOfMemory * computers::getPrice();
}

Because comp and inhComp are two different computers with two different price tags.
Thank you for your response, but servers is a derived class. It is derived from computers class. price is protected member of computers class. I thought that I could access protected members of the base class from derived class.
Yes, you can, and you do. The thing is that each object has its own copy of the variables, so if comp.price is set to 100.5 that will not affect the value of inhComp.price.
Last edited on
Topic archived. No new replies allowed.