How do I solve the one-way protection?

Hi!

I want to use the compiler to force correct initialization by forcing 
certain functions to be implemented in the subclasses (pure virtual 
functions only reach the first subclass). In my example below we can 
assume that the base class must be initialized by collecting, say class 
names.

class Base
{
public:
    Base();

protected:
    template<class T>
    void init_()
    {
       std::string cn = static_cast<T*>(this)->getClassName_();
       ... store cn in a list ...
    }
};

class Derived1 : public Base
{
public:
    Derived1() { init_<Derived1>(); }

protected:
    std::string getClassName_() const { return "Number 1"; }
};

class Derived2 : public Derived1
{
public:
    Derived2() { init_<Derived2>(); }

protected:
    std::string getClassName_() const { return "Number 2"; }
};


This does not compile unless I make getClassName_() public. Why is 
protection one-way and how can I get around it?


Thanks,
Daniel

-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
DeMarcus
8/6/2009 10:05:54 PM
comp.lang.c++.moderated 10706 articles. 11 followers. allnor (8507) is leader. Post Follow

3 Replies
169 Views

Similar Articles

[PageSpeed] 13
>    template<class T>
>    void init_()
>    {
>       std::string cn = static_cast<T*>(this)->getClassName_();
>       ... store cn in a list ...
>    }
> [...]
> This does not compile unless I make getClassName_() public. Why is
> protection one-way and how can I get around it?

When you convert "this" to a generic "T*" using static_cast<>, you no
longer benefit from being able to access protected members of T, even if
  T is the class you're calling from. For the simple reason that T can
now be anything, including "int" or "std::string". The compiler will
assume that you know what you're doing and T does have an accessible
(read: public) getClassName_() function, but no more than that.

You really don't need templates at all for what you're doing, that is
you can solve your problem either with templates, but no virtual
functions (in which case your member function needs to be public for the
reasons stated above), or without templates and with virtual member
functions, where you define getClassName_() as pure virtual in Base, and
simply call:

std::string cn = getClassName_();

in init_(). This will call the correct function for your objects.


-- 
Razvan Cojocaru
KeyID: 0x04CA34DE

      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Razvan
8/7/2009 12:37:54 PM
On Aug 7, 12:05 am, DeMarcus <use_my_alias_h...@hotmail.com> wrote:
> Hi!
>
> I want to use the compiler to force correct initialization by forcing
> certain functions to be implemented in the subclasses (pure virtual
> functions only reach the first subclass). In my example below we can
> assume that the base class must be initialized by collecting, say class
> names.
>
> class Base
> {
> public:
>     Base();
>
> protected:
>     template<class T>
>     void init_()
>     {
>        std::string cn = static_cast<T*>(this)->getClassName_();
>        ... store cn in a list ...
>     }
>
> };
>
> class Derived1 : public Base
> {
> public:
>     Derived1() { init_<Derived1>(); }
>
> protected:
>     std::string getClassName_() const { return "Number 1"; }
>
> };
>
> class Derived2 : public Derived1
> {
> public:
>     Derived2() { init_<Derived2>(); }
>
> protected:
>     std::string getClassName_() const { return "Number 2"; }
>
> };
>
> This does not compile unless I make getClassName_() public. Why is
> protection one-way and how can I get around it?
>
> Thanks,
> Daniel

I think you've got to declare Base a friend in each derived class.
At least that's what people sometimes do with Curiously Recurring
Template Pattern, and your case is somewhat similar to CRTP.

Note that unless getClassName_ should be called from more
derived classes, you should declare them private, not protected.


HTH,
   Andy.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Andrew
8/7/2009 12:40:44 PM
On 7 Aug, 05:05, DeMarcus <use_my_alias_h...@hotmail.com> wrote:
> Hi!
>
> I want to use the compiler to force correct initialization by forcing
> certain functions to be implemented in the subclasses (pure virtual
> functions only reach the first subclass). In my example below we can
> assume that the base class must be initialized by collecting, say class
> names.
>
> class Base
> {
> public:
>     Base();
>
> protected:
>     template<class T>
>     void init_()
>     {
>        std::string cn = static_cast<T*>(this)->getClassName_();
>        ... store cn in a list ...
>     }
>
> };
>
> class Derived1 : public Base
> {
> public:
>     Derived1() { init_<Derived1>(); }
>
> protected:
>     std::string getClassName_() const { return "Number 1"; }
>
> };
>
> class Derived2 : public Derived1
> {
> public:
>     Derived2() { init_<Derived2>(); }
>
> protected:
>     std::string getClassName_() const { return "Number 2"; }
>
> };
>
> This does not compile unless I make getClassName_() public. Why is
> protection one-way and how can I get around it?

There are two issues here: Why is protection one way? and How to get
the class name in the base class constructor?

Why is protection one way?
(A) I would think that most people would consider it unnatural to
allow special access to base classes. After all a base class is not
supposed to depend on the declaration of its derived classes (Although
it can depend on the definitions using virtual methods).
(B) What would you expect from:  Derived2()
{ init_<CompletelyUnrelated>(); }
(C) In general it is not valid to call ANY derived class member
function from a base class constructor because the derived object is
not constructed at that point. (This is why virtual methods aren't
virtual in a constructor)

How to get that class name to the base class constructor:
Short answer: Provide a protected constructor in the base class that
takes it as parameter.
Note that you never NEED to call a derived class member in a base
class constructor because it can never return anything that couldn't
have been passed as a parameter.
Occasionally it can be useful to have a STATIC derived class function
to compute the constructor parameter if this is complex.
In this specific example there is no reason for getClassName_ to not
be static as it does not depend on object state:

cn = T::getClassName_();


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Nick
8/7/2009 12:41:39 PM
Reply:
Similar Artilces:

[tao-users] one ways
People, I picked up the Addison Wesley book on corba titled "Advance CORBA programming with C++." Good read. In it, they claim that member function defined as one way means that its delivery is on a best effort with no guarantee on actually completion. Reminds me a bit of udp. Is this the case with TAO? Cheers. Steve. Stephen Adler wrote: >People, > >I picked up the Addison Wesley book on corba titled "Advance CORBA >programming with C++." Good read. In it, they claim that member >function defined as one way means that its delivery is on a best >effo...

solve the questions
i am beginer in vc++.i want help in the following questions. 1. How can i create database program using sql server through codings.If we want DSN name it also create through codings. if u have any easy sample program please sent the following mail id. nevis_soft@yahoo.co.in "nevis" <nevis_soft@yahoo.co.in> wrote in message news:e5011219.0405310413.6c3b9785@posting.google.com... > i am beginer in vc++.i want help in the following questions. > 1. > How can i create database program using sql server through codings.If > we want DSN name it also create through codi...

Can you solve this in matlab2009b 64 bit? (systems of equations to be solved using "solve")
Hi all, Can you solve the following in matlab 2009b 64 bit (macosx with snow leopard)? I get the errors given below the code. It takes a lot of time before Matlab gives the error. Where do I go wrong? %----------------------- syms p0 p00 p1 p2 cn cr dn dr a an ar bn br T tau real; myfun = [ -(tau*(2*an + 2*bn*cn - 4*bn*p1 - dn*tau))/2; -(tau*(2*ar + 2*br*cr - 4*br*p0 - dr*tau))/2; ((T - tau)*(T*dn - 2*an - 2*bn*cn + 4*bn*p2 + dn*tau))/2; ((T - tau)*(T*dr - 2*ar - 2*br*cr + 4*br*p00 + dr*tau))/2; an*p2 - an*p1 - ar*p0 + ar*p00 + bn*p1^2 - bn*p2^2 + br*p0^2 - br*p00^2 - bn*cn*p1 + bn*c...

NATting both ways
I have a 2811s doing many VPNs to partners and clients. These routers are on my "VPN" network off a PIX 525. I use static routes on the PIX to get the traffic from my networks to the appropriate router and then down the VPN. This has been the setup for years here. It works well and is predictable. All the VPNs are built using crypto maps. We use a combination of dynamic and static NATs (depending on connection direction) to a public address range we own specifically for these VPN NATs. Our partners and clients also use public address in the VPNs so we never have private range...

Another way of adding to a string (or output iterator)?
#include <string> #include <vector> #include <iostream> class Element { public: Element(std::string n) : name_(n) {}; std::string serialize() const { return "<element>" + name_ + "</element>"; } private: std::string name_; }; int main() { std::vector<Element> container; container.push_back(Element("Joe")); container.push_back(Element("Bob")); std::string all_serialized; std::vector<Element>::const_iterator iter; // Is there a cooler way of doing this lo...

quick lock your desktop with one press
Sales Email: ronnie@dengfengsoft.com Support Email: service@dengfengsoft.com Home Page: http://www.dengfengsoft.com/winlock/index.html Download Link: http://www.dengfengsoft.com/winlock/soft/ALock_setup.exe Screen Shot link: http://www.dengfengsoft.com/images/toobar_interface.jpg Program description: Prevent someone from using your computer Add a password to your file folders Computer Shutdown Boss key ALock V2.0.1 is a comprehensive solution for personal or plublicly accessible computers. Main features: 1.Lock your desktop with one click. It's fast and convenient. 2.Alock's ...

solving an array of equations with solve
Hello, I want to find zeros of a system of equations, eq=[eq(1),..,eq(n)]. But solve(eq) doesn't seem to work here, yet solve(eq(1),..,eq(n)) does. Suggestions? Thanks. ...

Need a solved genetic algorithm example problem for Optimization
Greetings. I am teaching a class on Engineering Optimization to undergraduate students. During the last week of classes, I want to cover some non-traditional optimization topics such as Simulated Annealing, Generic Algorithms, Taguchi Methods, and the like. I am looking for a fully solved example problem that uses genetic algorithms. The problem can involve any particular application - backpack problem, traveling salesman problem, and so on. It does not have to be fancy. However, I do need the m-code so that I can run it - and maybe single step in debug mode - in front of the class. Sadl...

What is the best way to move Samba PDC
I have a network, where the PDC is controlled by a SAMBA server. I would like to move the PDC functionality to another server (current PDC running on Red Hat 8 - would like to move to Fedora 6). What is the best way to do this? Can I just move the /etc/samba files to the new server? Thanks doverbey@optonline.net On Thu, 21 Jun 2007 21:48:08 GMT, "Overbey" <doverbey@optonline.net> wrote: >I have a network, where the PDC is controlled by a SAMBA server. I would >like to move the PDC functionality to another server (current PDC running on >Red Hat 8...

Re: best way to remove outliers #4
Steve Denham <stevedrd@yahoo.com> wrote <<< My personal feeling is that outliers should only be removed with high megatonnage nuclear devices... They are indicators in some sense--an indicator of poor data collection perhaps, or of a mixture of distributions, or of something novel that will eventually lead to many citations in the scientific literature. Anywho, most of the tests for outliers depend very heavily on distributional assumptions, and run into many of the same problems that tests of <insert desired distribution here> have: they are overpowered for large data...

Re: That new iMac is one HOT machine
"sigmond_" <sigmond@scientist.com> wrote in article e5f193d7b6827cf61666de811ad550ad@localhost.talkaboutmac.com on 8/31/04 2:02 PM: > "snit" <snit-nospam@CABLE0NE.NET> wrote in article > <4f349470fcb69b3cc7c08ce2ff8c5699@localhost.talkaboutmac.com> on 8/31/04 > 1:39 PM: > >> "Tom Elam" <tomelam@iquest.net> wrote in article >> tlk9j0prkd9dq3rq1hva4fjdu12po06o0i@4ax.com on 8/31/04 12:37 PM: >> >> >>> http://news.com.com/New+iMac+tries+to+play+it+cool/2100-1042_3- >>> 5331745.html?ta g=...

Multi-boot liveCDs solved!
Multi-boot liveCDs solved!!!!!!!! http://www.pcquest.com/content/enterprise/2005/105070101.asp (link from http://www.livedistro.org) Hats off to Mr. Anindya Roy for taking simple liveCDs and putting them together into different directories a big DVD and then make the DVD multi-boot so as to boot any of those liveCDs!!!!! I've been waiting a year for this solution - and its so simple! It could have (and probably have been) done ages ago. Now you can show burn a single DVD (or CD) with many liveCD distros as you want and the choose which one to run from menu. Never leave home without you...

US-VA-Reston: Security Systems Integrator: MLS/One way trusts, DCID 6/3; Perm (45294757608)
US-VA-Reston: Security Systems Integrator: MLS/One way trusts, DCID 6/3; Perm (45294757608) =========================================================================================== Position: Security Systems Integrator Reference: SMC01288 Location: Reston VA Duration: Perm Skills: 4 + years hands_on experience with operational systems using MLS and one way trusts, DCID 6/3 (and appropriate IC interpretations), IPT environment. Multi Level Security design, implementation, and/or operations. Six Sigma t...

Re: Why duplicating the last one?
Instructive Problem, Jue. When I tried to understand what the data step does, I thought "there ought to be a loop message" there and in fact when I copied your statements to my SAS session the message DATA STEP stopped due to looping showed up. Two things: variables obtained via SET are retained. That explains the duplicate which got written out as a result of the last "do nothing" iteration of the data step. As none of the datasets accessed by means of the SET statements was exhausted, the datastep continued [*1]. Thankfully SAS realizes the loop pretty soon an ends gra...

One to look out for...
Hi, I had commented out the following in my code: // oDCstep_bBrowser:server:ClearOrder() !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 19/8/2007 (I put the !!!s and the date in just so I can find the changes again if I need to ) I uncommented the code: oDCstep_bBrowser:server:ClearOrder() !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 19/8/2007 but didn't comment out the !!!!!s etc. When I came to compile the whole PC locked up on me - couldn't even do a three finger reset. Regards, Rob ...

Protect one single byte on Linux/x86 / sharing libraries / process mem. layout
Hello and a good day / night to all of you, wherever you are! :) As you might have guessed from the topic "Protect one single byte on Linux/x86 ..." I have some problems fully understanding memory protection on a x86 machine running linux. You also might have guessed that I'm not a native english speaker; I do apologize for any grammar or spelling mistakes. I did some research on the topic "memory protection" using google, wikipedia and searching newsgroups and right now I'm a little bit at a dead end because I don't know if the way I "understoo...

Solving an integral for an unknown function
Dear All, I wonder if anyone could let me know if there is a general solution to the following problem in Mathematica. Suppose the functions g[u,w] and h[w] are known. I want to find a function f[u] such that Integrate[g[u,w]*f[u],{u,0,1}]=h[w]. In addition I know that Integrate[f[u],{u,0,1}]=2 and Integrate[u*f[u],{u,0,1}]=1. Is it possible to solve the above for the unknown function f[u]? Of course there might be several solutions but I would be happy to find one. Many thanks in advance for any suggestions. Mikael ...

strings with moreover of one million of characters
Hi. Is possible use strings with moreover of one million of characters? I try using int() but the program keep blocked. Regards. Jose. > > Is possible use strings with moreover of one million of characters? >>> s = "A" * 2000000 >>> print len(s) 2000000 Works.. > I try using int() but the program keep blocked. What has int() with string to do? -- Regards, Diez B. Roggisch "Jos´┐Ż Carlos" wrote: > > Is possible use strings with moreover of one million of characters? > > I try using int() but the program keep blocked. Ma...

svm solve everything
MySVMLIB and MySEMLIB Copyright (C) 2007 Zhi-Jie He The LIB for SVM and OC-SVM training A fast and parameter-free SVM training algorithm with direct generalized performance control is achieved. By integrating kernel caching, shrinking and using second order information, a fast QP trainer is achieved. For traditional two-class SVM, the generalized error bound derived from SLT is calculated and minimized for the selection of parameters, with ZQP method and parallel method to speed up the process. For one-class SVM, a compression criterion is proposed and used to search the best kernel width au...

One Addition to john's web
Cycles (1.6k) Three LccWin-32 macro-implementations for measuring cpu-cycles: Author: Heinz van Saanen In the snippets section. John http://www.btinternet.com/~john.findlay1/ http://www.john.findlay1.btinternet.co.uk/ gclib (337k) I thought it would be handy to have the garbage collector that lcc-win32 uses as a static library, the Hans Boehm's garbage collector. I have extracted only essential files from the original package to compile with lcc-win32, you can download the original package from here. http://www.hpl.hp.com/personal/Hans_Boehm/gc/index.html The static library i...

Generate traffic with only one machine
I'm trying to generate Ip-traffic for testing purproses. As we now are testing multipoint performance of PLC networks I need some 4 to 8 endpoints to communicate but I can't afford to set up a dedicated linux box for each endpoint. After looking into kernel routing I found that the routing of packets can also depend of the incoming device. So basically I tried to set up a routing which send out any packet generated on this host to an external interface even if the IP address is assigned to interface attached on this host. Here is my solution: --------------- clapham:~# ip addr show 4: ...

designing a GA for solving general network routing problems.
Respected sir/madam Suppose i have a General computer networks independent of Topologies.I want to find the shortest path from source to destination through GA but using GA..... I don't know the use of GA chromosome encoding and fitness functions in matlab. what u suggest. thanking you ...........help me dear plz........ ...

solving with inverse functions/inexact coefficients
I'm trying to solve a set of simultaneous equations describing a laser cavity. A much simplified set of equations in Real unknowns F1, F2 and NU looks like this: F2 == Exp[0.76 NU] F1, F1 == 0.5 F2 Exp[0.76 NU], 0.5 F2 + NU == 15 They can be solved by hand very easily with two solutions, {F1=F2=0 && NU = 15} and {NU=0.46, F1=14.5, F2=29.1} Now Solve cannot solve these equations unless I change both instances of 0.76 to integers. Reduce seems to hang (or at least take too long to return and answer). Reduce can solve the problem quickly if I change both instances of 0.76 t...

Sorry ... I post one but I see two !
I post a message and I see two in the NG... I'll try to post some money XD HI In article <WeGdnYN2fvA7k0bXnZ2dnUVZ_gudnZ2d@westnet.com.au>, supervinx@libero.it says... > > I post a message and I see two in the NG... > I'll try to post some money XD try to increase the server time out setting Moussa -- The information contained in this post is copyright of the poster, and specifically may not be published in, or used by http://www.jlaforums.com ...

Old Acer extensa 367D password protected
Hey folks, I've been buying old Laptops on ebay and selling them again for something to do and a small addition to my retirement income. I just got one today that I can't get into the bios on because it has long ago been password protected. If there is any other way aside from replacing the bios, I would sure appreciate knowing it. It's a Acer Extensa 367D. Any and all help appreciated. -- Russ Keller russkeller@att.net On Tue, 02 Mar 2004 02:39:04 GMT, "Russ" <russkell@att.net> wrote: >Hey folks, >I've been buying old Laptops on ebay and selling th...