Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize char arrays in a constructor?

Tags:

c++

arrays

char

I'm having trouble declaring and initializing a char array. It always displays random characters. I created a smaller bit of code to show what I'm trying in my larger program:

class test
{
    private:
        char name[40];
        int x;
    public:
        test();
        void display()
        {
            std::cout<<name<<std::endl;
            std::cin>>x;
        }
};
test::test()
{
    char name [] = "Standard";
}

int main()
{   test *test1 = new test;
    test1->display();
}

And sorry if my formatting is bad, I can barely figure out this website let alone how to fix my code :(

like image 485
ShengLong916 Avatar asked May 02 '12 22:05

ShengLong916


People also ask

How do you declare an array in a constructor?

An array constructor can be used to define only an ordinary array with elements that are not a row type. An array constructor cannot be used to define an associative array or an ordinary array with elements that are a row type. Such arrays can only be constructed by assigning the individual elements.

Can you initialize in a constructor?

A class object with a constructor must be explicitly initialized or have a default constructor. Except for aggregate initialization, explicit initialization using a constructor is the only way to initialize non-static constant and reference class members.

How do you initialize a new char array?

Initializing Char Array A char array can be initialized by conferring to it a default size. char [] JavaCharArray = new char [ 4 ]; This assigns to it an instance with size 4.


1 Answers

Considering you tagged the question as C++, you should use std::string:

#include <string>

class test
{
    private:
        std::string name;
        int x;
    public:
        test();
        void display()
        {
            std::cout<<name<<std::endl;
            std::cin>>x;
        }
};
test::test() : name("Standard")
{

}
like image 60
mfontanini Avatar answered Oct 05 '22 07:10

mfontanini