Constructors

hi
I have two questions:

1. How to use constructors when creating an array?
for example:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
struct OBJ{
    OBJ(int x){
        cout<<x;//do something
    }
}
int main{
    OBJ* o=new OBJ[20];//Where should I write the parameters
    return 0;
}


2. How to use constructors with struct/class members?
example:
1
2
3
4
5
6
7
8
9
10
11
12
struct ENT{
    OBJ x;//it's the same OBJ struct as above
    ENT(){
        //here I get this error:
        //'OBJ' : no appropriate default constructor available
    }
};

int main(){
    ENT e;
    return 0;
}
You should provide a constructor with no arguments or with only optional arguments.
Last edited on
Is there any other way?
I don't find constructors with no arguments very useful.

2. How to use constructors with struct/class members?


1
2
3
4
5
struct ENT {
       OBJ x;
       ENT():x(4){
       }
};
Last edited on
1. How to use constructors when creating an array?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//this not the right solution, but can be useful

#include <iostream>
using namespace std;

struct ENT{
    static int defult;
    OBJ x;
    ENT():x(defult){
    }
};

int main{
    OBJ::defult = 3;
    OBJ* o=new OBJ[20];
    return 0;
}

To your first question there is no other way other than default constructor.
Topic archived. No new replies allowed.