Home > OS >  Can a base class access a derived class protected member in c ?
Can a base class access a derived class protected member in c ?

Time:07-20

I'm trying to get my base class currency. To access and return the string from it's derived class pound. My instructor specifically said it's a non public type (so I'm assuming a protected member would be the best here) and to NOT declare it in the base class. I'm having trouble making a function string getCurtype()to return the string and friending the derived class pound in my base class isn't not dong what I'm expecting it to do.

I'm guessing friending my derived class to the base class, doesn't give it access to it's protected members as it's only accisble in the derived class pound? Can someone please suggest me a way to set a getter string getCurType()for my string currencyType = "dollar" as a protected member in my derived class pound?

class currency{
 friend class pound;
 string getCurType(){return currencyType;};
 void print(){
    cout << "You have " << getPound() << " " << getCurType() << endl;
}
class pound : public currency{
protected:
   string currencyType = "pound";
}

Error:

test.cpp:11:34: error: 'currencyType' was not declared in this scope
        string getString(){return currencyType;};
                                  ^~~~~~~~~~~~
test.cpp:11:34: note: suggested alternative: 'currency'
        string getString(){return currencyType;};
                                  ^~~~~~~~~~~~
                                  currency

CodePudding user response:

Your design is backwards. Base classes should not need to know about derived classes other than the interface defined in the base. Define the interface you want to use in the base:

class currency{
public:    
    virtual string getCurType() = 0;       
    void print(){
        cout << "You have " << getCurType() << endl;
    }
};

class pound : public currency{
     string currencyType = "pound";
public:
     string getCurType() { return currencyType; }  
};

CodePudding user response:

You have misunderstanding here. To use currencyType in your base class it needs to be defined in that class. So in your case I would make the methods abstract in the abse class and implement it in the derived classes:

#include <iostream>
#include <string>

// this is your abstract base class (interface)
class currency
{
public:
    virtual std::string getCurType() const = 0;
    virtual void print() const = 0;
};

// implementation of pound
class pound : public currency
{
public:
    virtual std::string getCurType() const override
    {
        return "pound";
    }
    virtual void print() const override
    {
        std::cout << "You have " << getPound() << " " << getCurType() << std::endl;
    } 

private:
    int getPound() const 
    {
        return 3;
    }
};
  •  Tags:  
  • c
  • Related