Implementing virtual methods declared public as private

E

earthwormgaz

Ay up,

Can I do this? If not, why not :)

class CBase
{
public:
virtual void method() = 0;
};

class CDerived : public CBase
{
private:
virtual void method() { }
};

I might want to, because say, I don't want client code calling
method()?

Many thanks,

Gaz
 
K

Kai-Uwe Bux

earthwormgaz said:
Ay up,

Can I do this? If not, why not :)

class CBase
{
public:
virtual void method() = 0;
};

class CDerived : public CBase
{
private:
virtual void method() { }
};

You can do that.
I might want to, because say, I don't want client code calling
method()?

That, however, will not exactly be the result:

#include <iostream>
#include <ostream>

class CBase
{
public:
virtual void method() = 0;
};

class CDerived : public CBase
{
private:
virtual void method() {
std::cout << "private implementation\n";
}
};


int main ( void ) {
CBase * ptr = new CDerived ();
ptr->method();
}


Compiles and calls the private implementation of method().


Best

Kai-Uwe Bux
 
P

Paul Bibbings

earthwormgaz said:
Ay up,

Can I do this? If not, why not :)

class CBase
{
public:
virtual void method() = 0;
};

class CDerived : public CBase
{
private:
virtual void method() { }
};

I might want to, because say, I don't want client code calling
method()?

I'm struggling a little to understand under what circumstances - given
that you don't want client code calling method() - you would declare it
public in your base interface in the first place. Can you provide a
brief snippet by way of example of your thinking here?
Many thanks,

Gaz

Regards

Paul Bibbings
 
M

Michael Doubez

I'm struggling a little to understand under what circumstances - given
that you don't want client code calling method() - you would declare it
public in your base interface in the first place.  Can you provide a
brief snippet by way of example of your thinking here?

It might be used when CBase is not directly accessible.

Example:
class CFoo {
protected:
struct CBase {
virtual void method() = 0;
};
friend class CBar;
};

class CBar
{
public:
class CDerived: CFoo::CBase {
virtual void method() {
std::cout << "private implementation\n";
}
};
};

int main ( void ) {
CBar::CDerived derived;
// Error: static_cast<CFoo::CBase*>(&derived)->method();
}

Typically, this could be the case in some CRTP design.
 

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,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top