0

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

4
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by Stagnant
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';
        }
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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.