Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a class variable in one line?

In C++ how make a class variable in one line?
For example:
I have a class:

class point{
public:
 int x;
 int y;
};

How to make a variable in one line like java you can do new point(x, y), currently I do make a tmp and then push back to vector or something, are the simply way like java can do what I do in one line?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For creating a variable of type point on the stack you can use:

point myVariable{5,6};//this creates a point type variable on stack with x=5 and y=6;

So the complete program would look like:

#include <iostream>
class point{
    public:
        int x;
        int y;
};

int main()
{
    point myVariable{5,6};

    return 0;
}

The output of the above program can be seen here.
If you want to create a vector of point objects and then add objects into it, then you can use:

//create point objects
point p1{5,6};
point p2{7,8};

//create a vector
std::vector<point> myVector;

//add p1 and p2 into the vector
myVector.push_back(p1);
myVector.push_back(p2);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading