C++ syntax doubts

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tcsvikr
    New Member
    • Feb 2007
    • 18

    #1

    C++ syntax doubts

    consider the code given below:

    class base { //line1
    private: //line2
    const int a; //line3

    public: //line4
    base(int val = 0) : a(val) {} //line5
    int get_a() { return a; }
    }; // C4512 warning

    class base2 {
    private:
    const int a;

    public:
    base2(int val = 0) : a(val) {}
    base2 & operator=( const base2 & ) {}
    int get_a() { return a; }
    };

    int main() {
    base first;
    base second;

    // OK
    base2 first2;
    base2 second2;
    }


    What does the 'line5' signify?..I think ':' operator is for deriving a class from base class. But what is it doing for a method? I really could not understand .Can anyone help me???
  • bagapriya
    New Member
    • Feb 2007
    • 12

    #2
    Originally posted by tcsvikr
    consider the code given below:

    class base { //line1
    private: //line2
    const int a; //line3

    public: //line4
    base(int val = 0) : a(val) {} //line5
    int get_a() { return a; }
    }; // C4512 warning

    class base2 {
    private:
    const int a;

    public:
    base2(int val = 0) : a(val) {}
    base2 & operator=( const base2 & ) {}
    int get_a() { return a; }
    };

    int main() {
    base first;
    base second;

    // OK
    base2 first2;
    base2 second2;
    }


    What does the 'line5' signify?..I think ':' operator is for deriving a class from base class. But what is it doing for a method? I really could not understand .Can anyone help me???


    STATEMENTS COMING AFTER // IS USER FRIENDLY COMMENTS......

    Comment

    • horace1
      Recognized Expert Top Contributor
      • Nov 2006
      • 1510

      #3
      this is a constructor
      Code:
      base(int val = 0) : a(val) {} //line5
      where : a(val) is an initialisation list which initialises the data member a to the value of parameter val (which will default to 0 if non is supplied) see
      http://www.cprogrammin g.com/tutorial/initialization-lists-c++.html

      Comment

      Working...