Newbie problem in C++[Solved]

5 posts

Flag Post

I’m having trouble figuring why the output is different from what I had imagined.
I have two classes, one is the base class, and one is inherited from the base class. They both have different headers and cpp files. Sorry if this looks really messy, this would be my first time posting code here in the forums.

 SubClass::SubClass(int a)
{
     BaseClass(a);
} 

SubClass::getNumber()
{
    return BaseClass::getNumber();    //where the base class getNumber() returns the integer variable number.
}

//in a different cpp file
BaseClass::BaseClass(int a)
{
     number=a;   //number is a private member of the base class.
}

//in main.cpp
void main
{
     SubClass Sub1(123);
     cout<< Sub1.getNumber();  //this gives me -858993460 instead of 123.
}

Assuming I included the correct header files and such, why would this not give me 123? Thank you in advance.

 
Flag Post

Because your program doesn’t understand that you are trying to assign a value to your base class.

the actual code would be
SubClass::SubClass(int a):BaseClass(a){}

Hope it helps!

 
Flag Post

Ah, thank you so much! It works now.

 
Flag Post

No problem!

SHort explanantion; By the time you actually reach the functions in your constructor the baseclass constructor is already long gone

 
Flag Post

That’s what I figured since I experimented by putting a cout<< number; in the BaseClass part (and it gave me 123). However, the end result still gave me the huge negative number. Glad to know how to get it working as intended.

Thanks again!