0

I'm trying to implement a new class which suppose to have an array like so:

class myclass { 
    OtherClass<something1, something2>* array;  
   ....   
}

I want my c'dor to create myclass with an array of size=k of OtherClass. How can I do that? Thanks!

2 Answers 2

3

Like this:

#include <vector>

class myclass
{
    std::vector<OtherClass<something1, something2>> array;

public:
    explicit myclass(std::size_t n) : array(n) { }
};
Sign up to request clarification or add additional context in comments.

5 Comments

is there a way to do so without using vector?
Good to know some people use explicit ;)
@BobSacamano: Yes, but it requires a lot more effort for zero gain.
@BobSacamano if you don't want to use a vector then use std::array.
@BobSacamano: If you have to ask, then no. Vector is what you want, trust me, I'm a fish.
0

If you really want to use an array, you should have something like this (not recommended):

class myclass {
    OtherClass<Something1, Something2>* ptr_to;
public:
    myclass(std::size_t sz): ptr_to(new OtherClass<Something1, Something2>[sz]) {}
    ~myclass(){ delete[] ptr_to; }
};

This poses additional problems: move semantics are not very intuitive for types with pointers inside them. A better suggestion would be to use vector, as Kerrek pointed out above.

Comments

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.