473,804 Members | 2,148 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

class initialized array

Hi

how can I initialize a const char* myarr[] in a class constructor?

class Myclass {
const char* myarr[] = { "abc", "def" };
....
};
Myclass::Myclas s():
myarr[]( ??? )
{}

thanks
Nov 8 '06 #1
14 2116
Gary Wessle wrote:
how can I initialize a const char* myarr[] in a class constructor?
You cannot. Nobody can. No way to do that.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Nov 8 '06 #2
You need to add the static keyword.

class MyClass
{
public:

MyClass(){}
~MyClass(){}

static const char * myarr[];
};

const char * MyClass::myarr[] = {"abc", "def" };

Nov 8 '06 #3
Gary Wessle wrote:
how can I initialize a const char* myarr[] in a class constructor?

class Myclass {
const char* myarr[] = { "abc", "def" };
...
};
Myclass::Myclas s():
myarr[]( ??? )
{}
Use a vector of strings rather than an array of char pointers
(http://www.parashift.com/c++-faq-lit...html#faq-34.1), and
then use an initializer helper class:

template<typena me T>
class Initializer
{
vector<Tv_;
public:
Initializer( size_t reserveSize=0 ) { v_.reserve( reserveSize ); }
Initializer& Add( const T& t ) { v_.push_back(t) ; return *this; }
operator vector<T>() const { return v_; }
};

class Myclass {
const vector<stringmy arr;
public:
Myclass()
: myarr( Initializer( 2 )
.Add( "abc" )
.Add( "def" ) )
{}
};

Cheers! --M

Nov 8 '06 #4
XtremDev wrote:
You need to add the static keyword.

class MyClass
{
public:

MyClass(){}
~MyClass(){}

static const char * myarr[];
};

const char * MyClass::myarr[] = {"abc", "def" };
What if it's not static data?

Cheers! --M

Nov 8 '06 #5

mlimber a écrit :

What if it's not static data?

Cheers! --M
your solution ;o)

Nov 8 '06 #6
Gary Wessle wrote:
...
how can I initialize a const char* myarr[] in a class constructor?

class Myclass {
const char* myarr[] = { "abc", "def" };
...
};
Myclass::Myclas s():
myarr[]( ??? )
{}
...
In this context arrays support only one initializer syntax: '()'-initializer,
which leads to zero-initialization.

In your case one way around is to declare the array with explicitly specified size

class Myclass {
const char* myarr[2];
...
};

and use assignment instead of initialization

Myclass::Myclas s()
{
myarr[0] = "abc";
myarr[1] = "def";
}

--
Best regards,
Andrey Tarasevich
Nov 8 '06 #7
Andrey Tarasevich wrote:
Gary Wessle wrote:
...
how can I initialize a const char* myarr[] in a class constructor?

class Myclass {
const char* myarr[] = { "abc", "def" };
...
};
Myclass::Myclas s():
myarr[]( ??? )
{}
...

In this context arrays support only one initializer syntax: '()'-initializer,
which leads to zero-initialization.

In your case one way around is to declare the array with explicitly specified size

class Myclass {
const char* myarr[2];
...
};

and use assignment instead of initialization

Myclass::Myclas s()
{
myarr[0] = "abc";
myarr[1] = "def";
}
Right, although probably the pointers should almost certainly be const
also
(http://www.parashift.com/c++-faq-lit...html#faq-18.1),
which would eliminate this possibility.

Cheers! --M

Nov 8 '06 #8
mlimber wrote:
>...
and use assignment instead of initialization

Myclass::Myclas s()
{
myarr[0] = "abc";
myarr[1] = "def";
}

Right, although probably the pointers should almost certainly be const
also
...
That's something only the OP knows.

--
Best regards,
Andrey Tarasevich
Nov 8 '06 #9

Gary Wessle wrote:
Hi

how can I initialize a const char* myarr[] in a class constructor?

class Myclass {
const char* myarr[] = { "abc", "def" };
...
};
Myclass::Myclas s():
myarr[]( ??? )
{}

thanks
You could deal with allocating a pointer in the ctor body.
But thats old school stuff and frankly: much more work and way too
fragile.
You can only initialize an array with default values.
example:

template< typename T, const size_t Size >
MyClass
{
T array[ Size ];
MyClass() : array() { } // init elements to
// whatever the default T() might be
};

A std::string doesn't suffer from that handicap.

#include <iostream>
#include <ostream>
#include <string>

template < typename T >
class MyClass
{
T m_t;
public:
MyClass(const T& t) : m_t(t) { }
friend
std::ostream&
operator<<(std: :ostream& os, const MyClass& r_my)
{
return os << r_my.m_t;
}
};

int main()
{
MyClass< std::string instance("abc def");
std::cout << instance << std::endl; // so simple

return 0;
}

Nov 8 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

106
5620
by: A | last post by:
Hi, I have always been taught to use an inialization list for initialising data members of a class. I realize that initialsizing primitives and pointers use an inialization list is exactly the same as an assignment, but for class types it has a different effect - it calls the copy constructor. My question is when to not use an initalisation list for initialising data members of a class?
13
2393
by: Bryan Parkoff | last post by:
I have created three classes according to my own design. First class is called CMain. It is the Top Class. Second class and third class are called CMemory and CMPU. They are the sub-classes. Two sub-classes have the relationship to communicate back and forth through this pointer. The pointer is responsible inside Top class for allocating and deallocating two sub-classes. CMemory class is responsible to allocate and deallocate memory...
2
5580
by: Fred Zwarts | last post by:
If I am right, members of a class that are const and not static must be initialized in the initialization part of a constructor. E.g. class C { private: const int I; public: C(); };
5
4578
by: Jim Langston | last post by:
What I want to do: have a vector of ints in my class initialized with 0 to 499 which will later be pushed/popped out of the vector by instances. What I have: class CParticleStream // Yes, I know you wouldn't use 'C' { private: static std::vector<int> PSArray; public:
17
2677
by: Mark | last post by:
uhhmmm... not really sure how to word this. i cant get get this to compile.. i'm not sure what the proper syntax to do this is.. hopefully it's self explanatory. here's my class: ------ class TileMap { public:
14
1452
by: Qwert | last post by:
Hello, if you have an array with some class as element type and a same sized array with some structure as element type, and that class and structure have the same fields (for example 10 integers), is it correct to assume that the array with the classes uses less memory (than the array with structures) before the objects are initialized (X bytes per object) and uses more memory after all the objects are initialized (same fields + X bytes...
12
2985
by: jimmij | last post by:
Hi, Please look at the code bellow /*******************/ class ctab { private: static const unsigned n=48;
5
2464
by: partha.p.das | last post by:
Here is my class: class MyClass { public: MyClass(); ~MyClass(); private:
14
1887
by: Glen Dayton | last post by:
While looking at some old code I ran across a snippet that increments a pointer to access different members of a structure: .... struct Badness { std::string m_begin; std::string m_param1; std::string m_param2; std::string m_end;
3
2315
by: Stephen Torri | last post by:
Below is a class that is suppose to represent a segment of memory or a contents of a binary image (e.g. ELF executable). I have started to read Modern C++ Design and thought the best way to ensure I was understanding the chapter on policy classes was to attempt to apply them to my project. I understand the general concept of policies but I lack the knowledge and wisdom of how to identify them in an existing project. So I figured to get an...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10088
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6862
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5529
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3831
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.