Re: passing const ptr argument

From: Gianni Mariani (gi2nospam_at_mariani.ws)
Date: 08/11/04


Date: 11 Aug 2004 04:33:41 EDT

Anthony wrote:
> Hi,
> I want to write protect an argument that is passed by reference.
> But I still want to be able to call members of that argument.
> E.g. code (bottum) will gives the following compiler error:
> writeProtEvt.cpp: In member function `virtual void A::print(const B*)':
> writeProtEvt.cpp:24: error: passing `const B' as `this' argument of `virtual
> void B::print()' discards qualifiers
>
> Can anyone explain how to do this the right way?
>
> thanks in advance,
> Anthony Lansbergen
>
> // -------------------------------------------------------------------------
> ---
> #include <ostream.h>
> Class B
> {
> public:
> virtual void print()
Try this :

virtual void print() const
{
    cout << "printB" << std::endl;
}

Note the const at the end of the function decl. This indicates that the
  "this" parameter to the function is const.

> {
> cout << "printB" << std::endl;
> }
> };
>
> class A
> {
> public:
> virtual void print(const B* b)
> {
> cout << "printA" << std::endl;
> b->print();
> }
> };
>
> main()
> {
> cout << "test" << std::endl;
> A* a;
> B* b;
> a = new A();
> b = new B();
> a->print(b);
> }
>
>
>



Relevant Pages

  • Re: objects as parameters
    ... In message, Anthony C ... >the reference parameter is there, ive passed it in, unless im doing ... not link or does not execute as expected? ... forget pointers ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Different between operator comparision and .Equals(x)
    ... Anthony wrote: ... The '==' operator for reference types is by default a reference ... Only if the two values refer to the same object does it ... The Equals method is virtual, and thus is selected by dynamic dispatch ...
    (microsoft.public.dotnet.framework)
  • Re: TEM spot sizes
    ... Lasers, by Anthony E. Siegman, is a good reference. ...
    (sci.optics)