Hi all.
I would like to implement a hierarchy of cl***** to print
some messages to the screen. At present I would like to
use a base class with default behaviour, which then might
be overloaded to handle application-specific situations.
One relevant scenario is to use some GUI toolkit to print
the message in some sort of graphics widget.
Below is an outline of my naive idea to accomplish this.
The base class defines the default interface. The compound
class is some class which contains an internal class,
compond::derived, which is intended to implement
GUI-specific behaviour by accessing internal methods
in the widget. In a sense, the derived class acts as a
backdoor ito the compound class.
The general idea works, as the free function accepts
arguments of both base type and compound::derived
type.
However, the crux of the idea doesn't work, as the
compound::derived::print() method will not compile if
one tries to access the compound::i variable (see the
tagged line).
Is there a way to make this idea work?
Is there some other pattern which is better suited
to achieve the end goal?
I see no problems achieving this by declaring a
derived class outside compund which is declared
to be a friend of compound. But then, I have some
very vague recollection of having read somewhere
in ancient pre-history (some time in the mid '90s)
that the friend keyword is a bit dangerous as it
grants outsiders access to private parts, and is
thus best avoided.
Is this view still valid?
Rune
//////////////////////////////////////////////////////////////////////////////////////////
#include <iostream>
class base{
public:
virtual void print(){std::cout << "Base class" << std::endl;};
};
void print(base& b)
{
std::cout << "Free function: ";
b.print();
};
class compound{
private:
int i;
public:
compound(){i=1;};
class derived: public base{
public:
virtual void print(){std::cout << "Derived class";
std::cout /*<< i */ << std::endl;}; //<<<<<
=======
};
derived compound_backdoor;
void print(){compound_backdoor.print();};
};
int main(int argc, char* argv[])
{
base b;
b.print();
print(b);
compound c;
c.compound_backdoor.print();
print(c.compound_backdoor);
return 0;
}
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|