0

How to create Objects array or Classes array in C++?

I mean,How to make it so that you do not create objects manually like here:

Prozessor Obj1;
Prozessor Obj2;

I mean, that I don't want to create 10 objects manually. But by a cycle for or while?

#include <iostream>
using namespace std;


class Prozessor
{
  private:
  char marka[20];
  float chastota;  
  float cash;
  float vartist;

  public:

  void setProzessor()
    {
        cout << "Input brand: ";
        cin >> marka;
        cout << "Input chastotu : ";
        cin >> chastota;
        cout<<"Input number of cash:";
        cin>>cash;
        cout<<"Input vartist:";
        cin>>vartist;
    }
  void showProzessor()
  {
    cout << marka << " " << chastota <<" "<< cash << " " << vartist <<endl;

  }
};

int main()
{
   Prozessor Obj1;
   Prozessor Obj2;
   cout<<"vvedit dani"<<endl;
   Obj1.setProzessor();
   Obj2.setProzessor();

   Obj1.showProzessor();
   Obj2.showProzessor();

  return 0;
}

2 Answers 2

3

You can make a std::vector or std::array depending on if you know the size at compile time.

std::vector<Prozessor> prozessors;
for (int i = 0; i < 10; ++i)
{
    Prozessor prozessor;
    prozessor.SetProzessor();
    prozessors.push_back(prozessor);
}
Sign up to request clarification or add additional context in comments.

2 Comments

IMO a note about the constructor (being able to default-construct elements) and maybe emplace_back would be helpful
Thanks, how to do that by array, like structure array?
0

you can declare arrays in the same way you doit with struct or default types

struct Point { };
class Prozessor { };

int main()
{
    // an array of ints
    int arrint[10];
    // an array of Points
    Point arrPoint[10];
    // an array of Objects of the class Prozessor
    Prozessor arrProzessor[10];

    return 0;
}

nowadays we have more options to do that

vector is one that allows you to manage set of data without previously knowing the size of the container

std::vector<Prozessor> vectorOfProzessors;

1 Comment

Correct, but std::vector and std::array are better choices.

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.