Good Morning,

I just want to know how to implement a body initilization in a class. Below is the class information.

class  A
{
private: 
    const int size;         //a const data member
    char *cat; 
public: 
    A();                    //default constructor
    A(const int n);         //constrcutor with parameter
    void print();           //print A
    ~A(){delete[] cat;};    //destructor
}; 

A::A():size(100)            //head initialization of size
{
    cat = new char[size]; 
    strcpy(cat, "I see a head initialization."); 
}

A::A(const int n): size(n)
{
    cat = new char[n]; 
    if (n>50)
        strcpy(cat, "Meow, meow, another head initialization.");
    else
        cat[0]='\0';
}

void A::print()
{
    cout<<"size is => "<< size<<endl; 
    cout<<"cat is => " <<cat<<endl; 
}

Thank you

Recommended Answers

I think you are supposed to use your constructor to initialise your stuff.

Jump to Post

All 4 Replies

I think you are supposed to use your constructor to initialise your stuff.

you mean this ? A(const int n) : size(n),cat(0) {}

or something like this

A(const int n) : size(n),cat(new char[n]) {
    if (n>50)
        strcpy(cat, "Meow, meow, another head initialization.");
    else
        cat[0]='\0';
        }

You would initialize member variables in their member functions or constructor. You overloaded your constructor, meaning you a normal constructor (without param.) and an overloaded constructor (with param.). Either one of them is fine depending on how you want your program written.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.