0

How do I switch both parameters of the class to the object that I am creating? What is the syntax? (They must receive all the same parameters)

#include <iostream>

using namespace std;

class MyClass
{
    public:
        MyClass(int x,int y):value(x),value2(y)
        {
            //nothing
        }
        int value=10;
        int value2;
};

int main()
{
    MyClass ob1[5]; //Here! What is the correct syntax?
    cout << ob1[0].value << endl;
    return 0;
}
4
  • 1
    Possible duplicate of Objects with arguments and array Commented Apr 9, 2017 at 15:32
  • Would this work? MyClass ob1[5] = {(1,1),(2,2),(3,3),(4,4),(5,5)}? OR MyClass ob1[5] = {MyClass(1,1), MyClass(2,2), MyClass(3,3), MyClass(4,4), MyClass(5,5)} Commented Apr 9, 2017 at 15:32
  • FWIW, std::vector has a constructor to create N copies of something. It means an allocation and everything, though. Commented Apr 9, 2017 at 15:42
  • @George you're right, sorry, I had to specify... however, they had to be all the same! Thanks a lot to everyone! Commented Apr 9, 2017 at 15:52

2 Answers 2

2

You can use

MyClass ob1[] = {{1,2},{2,3},{3,4},{4,5},{5,6}};

(if you're using C++11 or later).

However, it would be better to use a std::vector or std::array.

Sign up to request clarification or add additional context in comments.

1 Comment

Not if the constructor is marked explicit though. Just nitpicking.
-1

Try these two

 MyClass ob1[5] = {{1,1},{2,2},{3,3},{4,4},{5,5}};

OR

MyClass ob1[5] = {MyClass(1,1), MyClass(2,2), MyClass(3,3), MyClass(4,4), MyClass(5,5)};

2 Comments

Are you sure about the first one?
Yeah, the first one needs braces rather than parentheses.

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.