GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 18-Jun-2004, 05:05
pablowablo pablowablo is offline
New Member
 
Join Date: Apr 2004
Posts: 24
pablowablo is on a distinguished road

How to initialize an array in a class definition or in constructor?


Let's say I have a class called Foo having a constant 2D integer array. And I want to initialize its values in the class definition or constructor... How should I do this? I always get an error when I try initializing it in the declaration or in the constructor


INITIALIZING IN THE DEFINITION

CPP / C++ / C Code:

class Foo
{
    const int twoD[2][2] = { {0,1}.{1,2}};
};


I get a syntax error when I do this.


INITIALIZING IN THE CONSTRUCTOR
CPP / C++ / C Code:

class Foo
{
   int twoD[2][2];
};

Foo::Foo()
{
  twoD[2][2] = { {0,1},{1,2}};
}

I also get an error when I do this, and when I try to declare it as extern in the definition, it doesn't help... anyone can help me out?
  #2  
Old 18-Jun-2004, 08:39
machinated machinated is offline
Regular Member
 
Join Date: Mar 2004
Location: victoria, canada
Posts: 324
machinated has a spectacular aura aboutmachinated has a spectacular aura about
you can't define anything in a class. you may only declare it. that's why constructor is a good idea. However since your array has already been declared in the class, you may not use the initializer list. Here's the correct way:

CPP / C++ / C Code:
class Foo
{
   int twoD[2][2];
   Foo();
};

Foo::Foo()
{
  twoD[0][0]=0;
  twoD[0][1]=1;
  twoD[1][0]=1;
  twoD[1][1]=2;
 //or run nested for loops
}
__________________
spasms!!!
  #3  
Old 18-Jun-2004, 08:45
pablowablo pablowablo is offline
New Member
 
Join Date: Apr 2004
Posts: 24
pablowablo is on a distinguished road
hey thanks for the reply!

I guess there's no easier way to do it... I wanted to make my code clean.

Thanks again
Quote:
Originally Posted by machinated
you can't define anything in a class. you may only declare it. that's why constructor is a good idea. However since your array has already been declared in the class, you may not use the initializer list. Here's the correct way:

CPP / C++ / C Code:
class Foo
{
   int twoD[2][2];
   Foo();
};

Foo::Foo()
{
  twoD[0][0]=0;
  twoD[0][1]=1;
  twoD[1][0]=1;
  twoD[1][1]=2;
 //or run nested for loops
}
  #4  
Old 18-Jun-2004, 08:50
dsmith's Avatar
dsmith dsmith is offline
Senior Member
 
Join Date: Jan 2004
Location: Utah, USA
Posts: 1,351
dsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of lightdsmith is a glorious beacon of light
Quote:
Originally Posted by pablowablo
Let's say I have a class called Foo having a constant 2D integer array. And I want to initialize its values in the class definition or constructor... How should I do this? I always get an error when I try initializing it in the declaration or in the constructor


INITIALIZING IN THE DEFINITION

CPP / C++ / C Code:

class Foo
{
    const int twoD[2][2] = { {0,1}.{1,2}};
};


I get a syntax error when I do this.


INITIALIZING IN THE CONSTRUCTOR
CPP / C++ / C Code:

class Foo
{
   int twoD[2][2];
};

Foo::Foo()
{
  twoD[2][2] = { {0,1},{1,2}};
}

I also get an error when I do this, and when I try to declare it as extern in the definition, it doesn't help... anyone can help me out?

I don't think this is possible. C++ does not allow you to initialize a function member which in turn would make that static inside a class. A class is not meant to have any static variables.

The only time that you can initialize an array is at the time that you define it. For that reason, the second one is invalid. The only work around that I can see is to assign the integers one at a time...

Someone else may have an idea though...
  #5  
Old 18-Jun-2004, 17:12
dabigmooish's Avatar
dabigmooish dabigmooish is offline
Member
 
Join Date: May 2004
Location: Baltimore (middle of Canton)
Posts: 167
dabigmooish will become famous soon enough
assigning the values using a loop, within your constructor works. I've done it before
  #6  
Old 18-Jun-2004, 17:21
pablowablo pablowablo is offline
New Member
 
Join Date: Apr 2004
Posts: 24
pablowablo is on a distinguished road
Thanks for all the help guys. I fixed it by looping in the constructor
  #7  
Old 11-Jun-2009, 02:28
ciacia ciacia is offline
New Member
 
Join Date: Jun 2009
Posts: 1
ciacia is on a distinguished road

Re: How to initialize an array in a class definition or in constructor?


actually its possible to write

CPP / C++ / C Code:
MyObject [2] = {MyObject(0, 3), MyObject (2,4)};
  #8  
Old 11-Jun-2009, 09:47
Howard_L Howard_L is offline
Regular Member
 
Join Date: Apr 2007
Location: Maryland/PA, USA
Posts: 802
Howard_L is a jewel in the roughHoward_L is a jewel in the roughHoward_L is a jewel in the rough

Re: How to initialize an array in a class definition or in constructor?


Can you give us a complete example of how you can get that to work?
  #9  
Old 11-Jun-2009, 12:23
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,218
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: How to initialize an array in a class definition or in constructor?


Since someone decided to revive this five-year-old thread, I thought I would add my .02 euros to try to throw some light on the original question.

The Original Poster wanted to initialize a const array in his class.

Now, if an array is const, it can't be changed, therefore all objects will have the same array values, so a static member is appropriate.

Regardless of opinions of others who said it can't be done and who said things like "classes aren't supposed to have" such stuff, It can be done, and, if you need it, I'll show a way.

Bottom line: Declare the array static. Static arrays, like any other static class variables, have to be initialized somewhere outside the class definition (not in the constructor). That's all there is to it:

CPP / C++ / C Code:
//
// This is foo.h
//
// davekw7x
//
#ifndef _FOO_H__
#define _FOO_H__
class Foo
{
  private:
    static const int twoD[2][2];
  public:
    int getTwoD(const int & i, const int & j);
};
#endif

CPP / C++ / C Code:
//
// This is foo.cpp
//
// davekw7x
//
#include <iostream>
#include <cstdlib>
using namespace std;
#include "foo.h"
//
// The static member array is declared once
// It's a const, and all objects have the same
// values for this array
//
const int Foo::twoD[2][2] = { {1,2},{3,4} };

//
// Access: Bail out if illegal index value
//
int Foo::getTwoD(const int & i, const int & j)
{
    if ((i < 0) || (i >= 2) || (j < 0) || (j >= 2)) {
        cerr << "Illegal index: valid values are 0 and 1" << endl;
        exit(EXIT_FAILURE);
    }
    return twoD[i][j];
}

CPP / C++ / C Code:
//
// This is test_static_array.cpp
//
#include <iostream>
#include "foo.h"
using namespace std;
int main()
{
    Foo foo;
    int i, j;
    for (i = 0; i < 2; i++) {
        for (j = 0; j < 2; j++) {
            cout << "twoD[" << i << "][" << j << "] = " << foo.getTwoD(i,j) 
                 << endl;
        }
    }
    cout << endl;

    cout << "Enter i and j: ";
    while (cin >> i >> j) {
        cout << "Now trying twoD[" << i << "]["
             << j << "]: " << flush;
        cout << foo.getTwoD(i,j) << endl;

        cout << endl;
        cout << "Enter i and j: ";
    }
    cout << "Goodbye for now." << endl;

    return 0;

}

Here's a run

Code:
twoD[0][0] = 1 twoD[0][1] = 2 twoD[1][0] = 3 twoD[1][1] = 4 Enter i and j: 0 1 Now trying twoD[0][1]: 2 Enter i and j: 1 1 Now trying twoD[1][1]: 4 Enter i and j: 1 2 Now trying twoD[1][2]: Illegal index: valid values are 0 and 1

This simple example gracelessly bails out of the program when invalid array index values are entered by the user.

A more attractive solution would have the access function throw an exception with a message that the user program could catch and recover without aborting the program, but the approach using the static array would be the same.

Regards,

Dave
  #10  
Old 11-Jun-2009, 16:07
L7Sqr L7Sqr is offline
Member
 
Join Date: Jul 2005
Location: constant limbo
Posts: 234
L7Sqr is a jewel in the roughL7Sqr is a jewel in the rough

Re: How to initialize an array in a class definition or in constructor?


Quote:
Originally Posted by davekw7x
Now, if an array is const, it can't be changed, therefore all objects will have the same array values, so a static member is appropriate.
That is not the case; const is not static.

For example:
CPP / C++ / C Code:
#include <iostream>

class Foo {
        const int twoD[2][2];
    public:
        Foo() : twoD((int[2][2]){{1,2},{3,4}}) {}
        Foo(int a,int b,int c,int d) : twoD((int[2][2]){{a,b},{c,d}}) {}

        void show () const {
            std::cout << "[[" << twoD[0][0] << "," << twoD[0][1] << "],["
                      << twoD[1][0] << "," << twoD[1][1] << "]]" << std::endl;
        }
};

int main () {

    Foo f1;
    Foo f2(4,3,2,1);

    f1.show ();
    f2.show ();

    return 0;
}

Quote:
Originally Posted by output
[[1,2],[3,4]]
[[4,3],[2,1]]

The initializer list can be used specifically for situations like this (base constructors, const members, etc).
__________________
My personal site: Utilities for text processing, debugging, testing and plotting
 
 

Recent GIDBlogProgramming ebook direct download available by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
shorthest path-another way Pandiani C++ Forum 6 09-May-2004 20:51
Creating 2d array madlynzz C++ Forum 1 20-Mar-2004 21:15
Speed up C++ code about 3d array! Truong Son C++ Forum 0 16-Mar-2004 22:52

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 17:11.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.