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 ?
The
m(i)in your constructor initializes themmember with valuei.Your example has the same outcome (and not behaviour) as
Initializing members using initializer lists as in your example is more efficient because the member’s constructor is called directly with parameter
iwhereas in the example above, the empty constructor ofmis called and thenmis assigned valuei.