Parameterized Constructor.
May 11, 2012 at 7:24am UTC
How do I call the parameterized constructor in the below programm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include<iostream>
using namespace std;
class my{
int a;
public :
my(){
a=8;
}
my(int k){
a=k;
}
void print(){
cout<<"Num:" <<a<<endl;
}
};
int main(){
my *myO;
myO=new my[4];
for (int i=0;i<4;i++){
myO[i].print();
}
cout<<endl;
system("pause" );
return 0;
}
if I write like this
myO=new my(2)[4];
this is considered an error.
May 11, 2012 at 7:41am UTC
if I write like this
myO=new my(2)[4];
this is considered an error.
In c++03 - you couldn't do that (you could not specify a constructor when
creating an array using new - although you could do this
myO=new my[4]() ;)
However, in C++11 - you can now do this (uniform initialization and initilalizer lists):
myO=new my[4]{2,6,3,101};
So read up on
C++11 Uniform Initialization & initializer lists
(there's lots of info about on the web)
Last edited on May 11, 2012 at 7:46am UTC
May 11, 2012 at 7:44am UTC
is there some difference for using C++11, I mean what else i will need to do for using C++11?
May 11, 2012 at 10:54am UTC
First you need a somewhat new compiler that supports the C++11 features you want to use. No compiler has full C++11 support yet. C++11 might not be enabled by default. For GCC you have to pass the flag -std=c++0x or -std=c++11 to the compiler.
Topic archived. No new replies allowed.