1

/* Hello Friends ... I am a beginner in C++ */

#include<iostream>
#include<conio.h>
using namespace std;

class A
{
    protected:
        int a,b;
    public:
        A():a(0),b(0){   }

};

int main()
{

 A *x;
 x = new A[20];
delete []x;
getch();
return 0;
}

My question is, How do we create a parameterised Constructor in Class A such that I could pass some default values while dynamically creating the array without using for loop. Also please tell me,What is the syntax of passing those values?

1

1 Answer 1

0

I think what you want is this:

#include<iostream>
#include<conio.h>
using namespace std;

class A
{
    protected:
        int a,b;
    public:
        A():a(0),b(0){   }
        A(int a, int b) : a(a), b(b) {  }

};

int main()
{
    A *x;
    x = new A[3]{ {10, 5}, {1, 2}, {4, 5} };
    delete []x;
    getch();
    return 0;
}

Note that you falsely had delete []a; in your code instead of the correct delete []x;.

The Constructor A(int a, int b) : a(a), b(b) { } initializes the member a and b with the parameter a and b respectively in the parameter list.

Then for the new call you give it a list with the arguments for the constructor grouped together in curly braces like this:

x = new A[3]{ {10, 5}, {1, 2}, {4, 5} };
Sign up to request clarification or add additional context in comments.

1 Comment

Note this requires a real C++11 compiler。

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.