Thread: Trouble understanding constructor

  1. #1
    Registered User
    Join Date
    Jan 2016
    Posts
    45

    Trouble understanding constructor

    I'm new to c++.
    Here's the constructor I'm trying to understand:

    Code:
    RealNum::RealNum(float initR) : r(initR)  {}
    I don't understand the part that's : r(initR)
    What does it mean?
    r is a float that holds a real number.
    If it was java code I would think r is a method name and initR is it's arguments.

    Here's the class interface
    Code:
    class RealNum {
      protected: 
        float r;
      public:                
        RealNum(float initR);
        float realPart();
        virtual void square(); 
        virtual void print();  
    };

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    It's called the initializer list. It initialises the variables specified in the list instead of assigning them. This can be important since initialising a variable calls its constructor, but assigning calls it assignment operator. For built-in types such as float, there is no difference between the two.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  3. #3
    Registered User
    Join Date
    Jan 2016
    Posts
    45
    Thanks, this was a great help: Initialization Lists in C++ - Cprogramming.com

    Quote Originally Posted by Elysia View Post
    It's called the initializer list. It initialises the variables specified in the list instead of assigning them. This can be important since initialising a variable calls its constructor, but assigning calls it assignment operator. For built-in types such as float, there is no difference between the two.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. I have trouble understanding this code
    By amirghannadan in forum C Programming
    Replies: 2
    Last Post: 02-29-2016, 08:07 PM
  2. Trouble understanding some code please help
    By Shinzu911 in forum C Programming
    Replies: 1
    Last Post: 02-19-2013, 09:01 PM
  3. Trouble Understanding the assignment given.
    By AlbyRang in forum C Programming
    Replies: 3
    Last Post: 03-30-2012, 01:51 AM
  4. a little trouble understanding
    By zema in forum C++ Programming
    Replies: 3
    Last Post: 11-05-2003, 05:49 PM
  5. having trouble understanding this statement
    By kes103 in forum C++ Programming
    Replies: 2
    Last Post: 10-03-2003, 09:00 AM

Tags for this Thread