/*
 * const_ptr.cpp: const methods of a class that holds a pointer
 *
 *   g++ -Wall -Wextra -ansi -pedantic const_ptr.cpp -o const_ptr
 *   ./const_ptr                        prints 25 61
 *
 * Add -DTRY=n to the g++ line to get one of the errors:
 *   1  a const method assigns to the field p
 *   2  fill gives the constant x another s1
 *   3  the const versions return const: both writes in fill fail
 *   4  the messages name the types of this, &p and &*p
 */
#include <stdio.h>

#ifndef TRY
#define TRY 0
#endif

struct s1 { int a, b; };

class Pointer_s1 {
    s1 *p;
public:
    Pointer_s1(s1 *ptr = 0) : p(ptr) {}
    ~Pointer_s1() { if (p) delete p; }
    s1 *operator=(s1 *ptr);
#if TRY == 3
    s1 &operator*() { return *p; }
    s1 *operator->() { return p; }
    const s1 &operator*() const { return *p; }
    const s1 *operator->() const { return p; }
#else
    s1 &operator*() const { return *p; }        /* p means this->p */
    s1 *operator->() const { return p; }
#endif
#if TRY == 1
    void Reset() const { p = 0; }
#endif
#if TRY == 4
    void InConst() const;
    void InPlain();
#endif
private:
    Pointer_s1(const Pointer_s1&) {}
    void operator=(const Pointer_s1&) {}
};

s1 *Pointer_s1::operator=(s1 *ptr)
{
    if (p)
        delete p;
    p = ptr;
    return p;
}

#if TRY == 4
void Pointer_s1::InConst() const        /* every line is wrong on purpose */
{
    static_cast<int>(this);
    static_cast<int>(&p);
    static_cast<int>(&*p);
}

void Pointer_s1::InPlain()
{
    static_cast<int>(this);
    static_cast<int>(&p);
    static_cast<int>(&*p);
}
#endif

void fill(const Pointer_s1& x)          /* x can't be changed here... */
{
    x->a = 25;                          /* ...but the s1 can */
    (*x).b = x->a + 36;
#if TRY == 2
    x = new s1;
#endif
}

int main()
{
    Pointer_s1 x;
    x = new s1;
    fill(x);
    printf("%d %d\n", x->a, x->b);
    return 0;
}
