Hey, I'm trying to put all the objects of my class into an array so it will be easier to display.. It doesn't work though! Here is the code:

#include <cstdlib>
#include <iostream>
#include "manager.h"
#include <windows.h>
using namespace std;

void displayManagers();

int main(int argc, char *argv[])
{
    displayManagers();
    
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}
void displayManagers()
{
   Manager m[1](10, "name", "name", "sfsf", 15, 45, 10);
}

main.cpp bad array initializer is the error message. Any any guys? Thanks in advanced

Dani AI

Generated

The compiler error comes from trying to declare an array and pass constructor arguments to it in one step. An array declarator cannot be followed by parenthesised constructor arguments, so the declaration in the original post fails. The practical solutions are: initialize the array with braced initializers, or use a container that constructs elements for you (preferred for a variable number of objects).

A fixed-size array (C++11 list-initialization) example:

Manager managers[1] = { {10, "name", "name", "sfsf", 15, 45, 10} };

This constructs one Manager in-place using brace initialization. It’s concise but only convenient for statically known, small sizes.

A more flexible, safer approach is std::vector:

#include <vector>

std::vector<Manager> managers;
managers.emplace_back(10, "name", "name", "sfsf", 15, 45, 10);

emplace_back constructs the object in-place (no temporary/copy). If many objects are expected, call managers.reserve(n) first to avoid costly reallocations and moves.

Notes tied to earlier replies: ’s idea of creating a temporary then assigning is valid but can add a copy; emplace_back avoids that. was correct to point toward brace initialization for arrays. If compilation still fails, verify the Manager class in manager.h — confirm a matching constructor exists and whether copy/move constructors are available (containers may move/copy elements on reallocation). Dynamic placement-new is possible for fine-grained control, but std::vector is the recommended, simpler solution for most cases.

Recommended Answers

All 2 Replies

I don't see neither your class Manager definition, nor array 'm' def, but I guess something like that, should work:

Manager man1=(10, "name", "name", "sfsf", 15, 45, 10);
m[1]=man1;

Try reading this on array intialization

It seems to me that you declare the array 'm' with an inital size of 1, but are trying to add more than one element to the array. I would give a constant size to the array that will be big enough to accomodate a substantial input. Also you must set the array = to the values which must be stored in curly braces{}. Refer to the link if my explanation was unclear.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.