0

I have a question. Is it possible to create multiple objects during run time for classes or structures?

#include<iostream>
#include<conio.h>
using namespace std;
struct node
{
       int no;
};

int main()
{
   int i;
   for(i=0;i<4;i++)
   {
                   struct node s[i];
   }
   cout<<"Enter the values";
   for(i=0;i<4;i++)
   {
                   cin>>s[i].no;
   }
   cout<<"The values are:";
   for(i=0;i<4;i++)
   {
                   cout<<s[i].no<<endl;
   }
   getch();
   return 0;
}

I tried the method above , but didn't succeed . Any help would be appreciated

4
  • 3
    Your program is a weird mix of C and C++. Prepending struct before a struct name is C-syntax, using namespace is C++-syntax. It's fine to use libraries from either in a C++ program, but I would urge you not to mix up C-syntaxism in there. Commented Oct 6, 2011 at 8:37
  • Oh thanks for correcting me, I am a newbie. I would correct these in future :) Commented Oct 8, 2011 at 16:35
  • I hope so :) Unfortunately it's a bit hard to learn on your own, if you can I suggest you pick a book (read the about C++ tag, it references a list). Commented Oct 8, 2011 at 16:39
  • Using struct in C++ is 100% permissible. C++ is not an object oriented language. It is a language that SUPPORTS type creation, some of which may or may not be classes for which instances would be objects. Commented Mar 17, 2017 at 1:37

4 Answers 4

5

replace

for(i=0;i<4;i++)
{
       struct node s[i];
}

with

 struct node s[4];

the way you wrote your program will not work. You defined the node array s inside a block so it will not be visible outside of that block.

If you want to dynamically allocate the memory you have to do something like:

 struct node *s = new node[YourDesiredSize];

or if you like the c style (not recommended):

 struct node *s;
 s = (node*)malloc(YourDesiredSize * sizeof (node));

and don't forget to free the memory.

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

3 Comments

Yes I am sure it would work as you stated but my problem is I am not sure of what the size would be,In such a case what can I use?
then you have to allocate the memory on the fly. Define your s as a pointer and use malloc to allocate how much you need.
Doesn't address the input or the fact that C++ is obviously the goal given the include.
1
for(i=0;i<4;i++)
{
 struct node s[i];
}

Here you create an array of nodes inside a for loop. This is local and only available in the for loop. In addition this will not compile as it is written because i is not a constant expression. Even however if you used the new operator to allocate the array as before it would only be available in the for loop.

Instead you should declare your array somewhere else :

 node s[4];

This will create an array of size 4 by calling the default c'tor of node. Then your code should work.

2 Comments

Yes I am sure it would work as you stated but my problem is I am not sure of what the size would be,In such a case what can I use?
You can use a std::vector<node> myNodes; Then simply use the pushback methods of the vector to add items. Vectors have the ability to resize themselves when there is need to. In addition if you have an estimation of how big the maximum size of the vector should be you can initialize it with an appropriate constructor. Finally bare in mind that when a vector resized itself this is an expesnive operation.
1

If you want to create instances of structs or classes at runtime you need to use the new operator.

struct node* n = new n[4]; // creates an array of 4 node structs

for( int i=0; i<4; ++i )
{
  n[i]->no = i;
}

Since this is dynamically allocated memory you are responsible for freeing it when the structs are no longer needed.

delete[] n; // free dynamically allocated memory - the brackets are needed because this an array

4 Comments

You should only use new when you need the object(s) to outlive the current scope, or when you're creating something whose size is variable or very large; use automatic variables when you can. If you do use dynamic allocation, it's best to use resource management classes, such as smart pointers and containers, to ensure the objects are correctly deleted - it's very easy to introduce memory leaks otherwise.
Absolutely right on all points, but in my opinion using smart pointers or any other memory management scheme it is advisable to know what dynamic memory allocation is.
Thanks Holger,can you give the syntax for classes? I tried googling with no results, I think I am not googling the correct terms. Syntax using new operator for Classes would be helpful
well I think I would be best if you got hold of a book presenting the basics of c/c++. In answer to your question, there is no special syntax for classes. Classes, structs, ints, double ... are types and with the new operator you are able to dynamically allocate memory for a type. So if node is a class allocating memory for one object of type node this is the syntax: node* n = new node();
0

That can be done with a native array of instances (of structures or classes) if you know the count of them, or you can used collections such as list or vector if you don't.

#include<iostream>
#include<list>

using namespace std;

struct node
{ 
    int no;
    node() { }
    node(int i) { no = i; }
};

int main()
{
    struct node * arrayOf4Nodes = new node[4];

    cout << "Enter four values: ";
    int i;
    for(i = 0; i < 4; i ++) {
        cin >> arrayOf4Nodes[i].no;
    }

    cout << "The values are:" << endl;
    for(i = 0; i < 4; i ++) {
        cout << arrayOf4Nodes[i].no << endl;
    }

    delete [] arrayOf4Nodes;

    // OR for unknown lengths

    cout << "Enter values ending with -1000 to exit: ";
    list<node> listOfNodes;
    while (true) {
        cin >> i;
        if (cin.eof() || i == -1000)
            break;
        listOfNodes.push_back(node(i));
    }

    cout << "The values are:" << endl;
    for (node n : listOfNodes) {
        cout << n.no << endl;
    }

    return 0;
}

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.