2 Tips of C++ Programming with const

1. Implicit type conversion and copy constructor

If you want to define your own copy constructor, you should define like that:

class Foo {
  Foo (const Foo& obj) {}

Pay attention to the const in the parameter declaration. If your copy constructor definition loses const (Sun's C++ compiler does NOT complain), your implicit type conversion member will fail to compile, though the copy constructor is not used in type conversion.

class Foo {
  Foo (Foo& obj) {}
  Foo (Bar *obj) {}

Foo test () { return new Bar(); }

On linux with g++, you will get the error messages as following:
  error: no matching function for call to ‘Foo::Foo(Foo)’
  ... ...
  error:   initializing temporary from result of ‘Foo::Foo(Bar*)’

On solaris with sun studio c++ compiler, you will get:
  Error: Cannot use Bar* to initialize Foo without "Foo::Foo(const Foo&)"

2. The reference of pointer and "this"

Look at this piece of code:

void test (Foo* &obj) {}
//void test (Foo* const &obj) {}

class Foo {
  void bar () { test (this); }

On linux with g++, you will get error messages as following:
  invalid initialization of non-const reference of type ‘Foo*&’ from a temporary of type ‘Foo* const’
  in passing argument 1 of ‘void test(Foo*&)’

On solaris with sun studio c++ compiler, you will get:
  Error: Formal argument obj of type Foo*& in call to test(Foo*&) requires an lvalue.

Seems that sun studio c++ compiler treats the & in "&obj" as the addressing operator, so it requires an lvalue (left value). If we uncomment the 2nd test () (which in blue), then in function bar (), we must call test ((Foo *const) this); or just comment out the 1st test (), so that we could pass the compiling.

For non const members or external functions, the type of 'this' is Foo *const, for const members, its type is const Foo *const.

One thought on “2 Tips of C++ Programming with const

Leave a Reply

Your email address will not be published. Required fields are marked *

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha