1
#include<iostream.h>
class test{
    int a;
    char b;
public:
    test()
    {
        cout<<"\n\nDefault constructor being called";
    }
    test(int i,char j)
    {
        a=i;
        b=j;
        cout<<"\n\nConstructor with arguments called";
    }
};
int main()
{
    test tarray[5];
    test newobj(31,'z');
};

In the above code snippet can we initialize values to tarray[5]?

1
  • For sure, the elements you initialize will call the appropriate constructor, and the ones you left uninitialized will be instantiated by default constructor. Commented May 31, 2010 at 6:52

1 Answer 1

7
test  tarray[5] = {test(1, 2), test(), test(5, 6), test()};

The fifth element will be initialized with default constructor.

//here length of array will be inferred from number of initializers,
//   so it's going to be 4
test  tarray[] = {test(1, 'a'), test(), test(5, 'b'), test()};
Sign up to request clarification or add additional context in comments.

4 Comments

tarray is an object of class test and it has its own int a and char b.how can we intializa the character
@anurag18294: tarray is an array of test s, not an instance of test. However, its members are instances of test. In other words, there is no tarray.b, only tarray[0].b, tarray[1].b, etc.
can we intialize it in this manner test tarray[5]={test(1,'a'),test(3,'b'),test(5,6),test(),test(4,'s')};
@anurag, sure, whatever test constructor can handle.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.