Click here to Skip to main content
15,893,644 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
void dooperation()
   {
       cout<<x+y;

   }

even though x ,y are now private menmbers of class addition ...why are they out of scope of member dooperation();

What I have tried:

#include <iostream>

using namespace std;
template<class T>
class calculator
{
    protected:
    T x;
    T y;
    public:
        calculator(T m,T n)
        {
            x=m;
            y=n;

        }
    virtual void dooperation()=0;
    

};

template<class T>
class addition: public calculator<T>
{
public:
    addition(T m,T n):calculator<T>(m,n)
    {

    }
    void dooperation()
    {
        cout<<x+y;
       
    }



};

int main()
{
    addition<int> add(3,4);
    calculator <int>* ptr;
    ptr=&add;
    ptr->dooperation();
}
Posted
Updated 12-Jun-18 20:09pm
Comments
[no name] 12-Jun-18 9:11am    
Quote: "why are they out of scope of member dooperation()"
What evidence do you have of this?

It is not related to private members here (you do not have any in your code) but to the fact that the names are non-dependant.

It is explained in detail at Standard C++ FAQ: Why am I getting errors when my template-derived-class uses a member it inherits from its template-base-class?[^] and provides the solution:
C++
void dooperation()
{
    cout << this->x + this->y;
}
 
Share this answer
 
Comments
[no name] 12-Jun-18 9:25am    
Good. The questioner does not state which compiler. My VC++ 2017 handles this fine (no warnings - correct output) albeit it appears in a non-standard way. The silent incorrect compilation potential is certainly a hazard.
Jochen Arndt 12-Jun-18 10:27am    
As said at the link (and elsewhere when searching for the topic):
"Perhaps surprisingly, the following code is not valid C++, even though some compilers accept it"

He probably uses the GNU compiler because that throws an error message about "out of scope members".
CPallini 12-Jun-18 10:26am    
5.
When you need external access to private members it is best to implement public getters. The returned value should be constant and by ref for avoiding problems and overhead.
C++
public:
const T& getX() { return x; }
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900