Thread: Prevent member variable from being modified after construction

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2004
    Location
    UK
    Posts
    109
    Quote Originally Posted by AH_Tze
    Code:
    Foo(int in): member(in) {
    }
    Ah. It works. But could you explain that syntax?

    I had tried:
    Code:
    Foo(int in) {
          member = in; 
    };
    and gotten an "illegal assignment of read-only data member" from dev-c++.

    I don't understand the difference between the two.
    In the first syntax the variable is initalised as it constucted. In the second the variable is initialised after it is constructed which is illegal since the variable is const.

  2. #2
    Registered User
    Join Date
    May 2003
    Posts
    82
    Ah. I'd seen something similiar using user-defined types, but I'd never seen a primitive data type being initialized that way. Very clever.

    Thanks all, and I am once again in Preludes debt.

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >but I'd never seen a primitive data type being initialized that way. Very clever.
    I would recommend getting into the habit of using the initialization list rather than assignment in your constructors. It's always legal, and often more efficient. Of course, it could be impractical if you have a huge number of members to initialize, but that's really a sign of bad design IMO.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  2. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 09:32 AM
  3. Outputting to a File Modified Text
    By alpha in forum C++ Programming
    Replies: 8
    Last Post: 11-24-2003, 08:39 PM
  4. Replies: 3
    Last Post: 10-10-2002, 07:34 AM
  5. Using 'if' with char arrays or string objects
    By c++_n00b in forum C++ Programming
    Replies: 36
    Last Post: 06-06-2002, 09:04 PM