Variable is undeclared, but why?

M

mailforpr

Here's an examble:

template<class C> struct S
{
C c;
};

template<class C> struct D
:public S<C>
{

void f(C temp)
{
c=temp;
}
};

int main()
{
D<int> i;
i.f(2);

return 0;
}


Error message (compiled with g++ 3.4):
In member function `void D<C>::f(C)':
error: `c' undeclared (first use this function)

D is a S, so D should have public access to c. But it hasn't. Does
someone know why that is so?
 
M

mailforpr

Okay, it does have access to c. I modified the code a bit:

void f(C temp)
{
S<C>::c=temp;
}

Is there any other way to access the member of a base class/struct?
Writing S<C>:: before each member is annoying.
 
F

flopbucket

Okay, it does have access to c. I modified the code a bit:

void f(C temp)
{
S<C>::c=temp;
}

Is there any other way to access the member of a base class/struct?
Writing S<C>:: before each member is annoying.

Well, you can use this->
 
V

Victor Bazarov

flopbucket said:
Well, you can use this->

You could also use 'using':

template<class C> class B {
protected:
C c;
};

template<class C> class D : public B<C> {
using B<C>::c; /// AHA!
public:
void foo(C cc) {
c = cc;
}
};

int main() {
D<int> di;
di.foo(42);
}

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top