0

I am trying to learn some OOP and I have a problem understanding the following program:

#include<iostream>
#include<conio.h>
#include<string.h>
using namespace std;

class A
{
public:
    A(int i) : m(i){}

    friend class B;

    friend void g_afiseaza_m();
private:
    int m;
};

class B
{
public:
    void afiseaza_m()
    {
        A a(250);
        cout<<"clasa B este prietena cu clasa A"<<endl<<" poate accesa membrul privat A::m"<<endl<<a.m<<endl;
    }
};

void g_afiseaza_m()
{
    A a(300);
    cout<<"functia g_afiseaza_m nu este un membru al clasei A dar este prieten"<<endl<<"poate accesa membrul privat A::m"<<endl<<a.m<<endl;
}

int main()
{
    B b;
    b.afiseaza_m();
    g_afiseaza_m();
    getch();
    return 0;
}

Can you please tell me what does this line do: public:A(int i) :m(i){} private: int m? I undestand that A is a constructor with the int parameter i, and that m is a private member of class A but I can't understand what is m(i) ? Is this a matter of syntax ?

Cristina Ursu
  • 201
  • 2
  • 6
  • 18
  • 1
    See this: http://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor – chris Nov 01 '12 at 16:06

3 Answers3

6

The m(i) in your constructor initializes the m member with value i.

Your example has the same outcome (and not behaviour) as

A(int i) {
    m = i;
}

Initializing members using initializer lists as in your example is more efficient because the member's constructor is called directly with parameter i whereas in the example above, the empty constructor of m is called and then m is assigned value i.

alestanis
  • 21,519
  • 4
  • 48
  • 67
5

That's a constructor initializer list, it initializes the member m of the class with the specified value.

It's there to prevent initialization followed by immediate assignment in some cases (not here).

Some members can only be initilized in the initializer list - const members, reference members, types that aren't default-constructable.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
5
A(int i) : m(i) {}
         ^^^^^^ this is called member-initialization list.

Here m(i) means m is being initialized with i.

If you have more members, say, x, y in your class, then you can write this:

A(int i) : m(i), x(i*10), y(i*i) {}

So all the 3 members are initialized before entering into the constructor body.

See these topics for more detailed answers:

Community
  • 1
  • 1
Nawaz
  • 353,942
  • 115
  • 666
  • 851