Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Set default value of array in constructor ? 2

Status
Not open for further replies.

Lim

Programmer
Aug 15, 2000
192
US
I can set default value for integer even for string (for me string is the same array of char's), but why I can not set default value for array of integer of two,
for example:
class A
{
public:
A (int A=1, char *strName="Noname", int aI[2] = {-1,-1})
{
m_A = A;
m_strQName = strName;
m_aI[0] = aI[0];
m_aI[1] = aI[1];
}
~A();
private:
int m_A;
QString m_strQName;
int m_aI[2];
}
This one is not working.
But I want to initialize my object in constractor by this call:
A oA(2,"Line");
And I would like that m_aI[2] will be set by -1.
How can I do this?

Currently I deleted default values in constarctor arguments and set them in Constructor body. And I use other function to set user's values in my object, but I don't like it, bacause user of my class should make extra call.
Thank you.
 
try some workaround

#include<iostream>
using namespace std;
class ttttt
{
public:
ttttt(char* c=&quot;hello&quot;,int* x=0)
{
if(x==0)
{
x=new int[2];
x[0]=-1;
x[1]=-1;
}

cout<<c<<&quot;-&quot;<<x[1]<<&quot;;&quot;<<x[1]<<endl;
delete[] x;
}
};
void main()
{
ttttt x;
} John Fill
1c.bmp


ivfmd@mail.md
 
why not do this...

int default_array[2]={-1,-1};

class A{
public:
A(int* ary=default_array){m_aI[0]=ary[0]; m_aI[1]=ary[1];}

private:
int m_aI[2];
};

Matt
 
Thank JohnFill.
Zyrenthian, thanks good one.
Other workaround is create second constructor.
I am moving from C to C++ and some things in C++ puzzled me. After experience with C I would like to see behind the syntaxes and understand what is really going on in code. And for me was not clear Why in C++ you can preset char array and can not any other with fixed size?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top