Member Initialization Lists
#include <iostream.h>
/*********************************************
File: constmember1.C
This program demonstrates the problem of
initializing const data members
*********************************************/
class ABC{
const int x;
const int y;
public:
ABC(int ,int );
void get_xy(int& ,int& );
};
ABC::ABC(int var1, int var2)
{
cout << "Constructing..." << endl;
x = var1;
y = var2;
}
void ABC::get_xy(int& var1, int& var2)
{
var1=x; var2=y;
}
int main()
{
int var1, var2 ;
ABC object1(10, 20);
object1.get_xy(var1, var2);
cout << "X = " << var1 << " Y = " << var2 << endl;
return(0);
}
Compile Time Error:
constmember1.C: In method `ABC::ABC(int, int)':
constmember1.C:20: assignment of read-only member `int ABC::x'
constmember1.C:21: assignment of read-only member `int ABC::y'
#include<iostream.h>
/*********************************************
File: constmember.C
This program demonstrates the use of member
initialization lists.
*********************************************/
class ABC{
const int x;
const int y;
public:
ABC(int ,int );
void get_xy(int& ,int& );
};
ABC::ABC(int var1, int var2) : x(var1), y(var2) // x and y are initialized
here
{
cout << "Constructing..." << endl;
}
void ABC::get_xy(int& var1, int& var2)
{
var1=x; var2=y;
}
int main()
{
int var1, var2 ;
ABC object1(10, 20);
object1.get_xy(var1, var2);
cout << "X = " << var1 << " Y = " << var2 << endl;
return(0);
}
Back to Previous Page
Document:
Local Date:
Last Modified On: