Question:
C++ inheriting protected member functions help?
2010-02-13 21:15:53 UTC
i'm reading C++ All-in-One Desk Reference for Dummies, and right now im stuck on a part about protected members in class and using them in dervived classes.

the book says that derived classes cant access private functions, but if you want derived classes to access member functions, and prevent other users from accessing them, you use "protected:"

however, i still get a compiler error (compiler is MinGW GCC; IDE is Code::Blocks)

here is the code i wrote to test it and i cannot see what i did wrong

#include

using namespace std;

class Vehicle
{
public:
int RandomPublicVariable;

protected:
void Drive()
{
cout << "vroom vroom!" << endl;
}

};

class DodgeViper : public Vehicle
{
public:
void CheckOutMyViper()
{
cout << "Yo check out my hot viper!" << endl;
}

};

int main()
{
DodgeViper MyCar;
MyCar.CheckOutMyViper();
MyCar.Drive();

return 0;
}

when i compile and run, i get the error "void Vehicle::Drive() is protected". i might have typed that error wrong, but you get the jist: it says Vehicle() is protected, and the book says derived classes can inherit protected functions. WTF?
Three answers:
Ratchetr
2010-02-13 21:38:58 UTC
Protected does just what the book says: It allows access to derived classes, but not others.



You didn't try to access Drive from the derived class. You DID try to access it from outside the class. But when you call it from main, you are the 'other' they are talking about....not allowed.



What you CAN do is override Drive in DodgeViper. And your override can call the base class Drive if it wants (doesn't have to, but it can).



Add this function to DodgeViper, and it will compile and run. It calls the base class Drive, then adds to it:



void Drive()

{

   Vehicle::Drive();

   cout << "VROOM ;-)" << endl;

}
?
2016-11-06 12:28:18 UTC
use "secure" modifier whilst inheriting... deepest contributors of the backside class can't be inherited. If u use secure modifier whilst inheriting all public contributors will replace into secure contributors of the derived class. Public contributors would nicely be accessed by using each and every of the training. yet secure contributors of a class can in common terms be get right of entry to by using the training which derive from it.
juliepelletier
2010-02-13 21:29:47 UTC
It will inherit the protected function but it'll remain protected.



If you place the call from withing your CheckOutMyViper() function, then it should work.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...