"say u have a class and want to create objects for that class, would you be able to use an array of objects for it or would u need to define each object created individually"
When you declare an array of objects, the default constructor will create each object in the array. Try this code and see what happens:
Code:
#include <iostream>
using namespace std;
class aclass
{
public:
aclass() //Default constructor
{
cout<<"Default constructor called."<<endl;
}
aclass(int n) //Constructor
{
cout<<"Constructor called."<<endl;
num = n;
}
private:
int num;
};
int main()
{
//Create single object with default constructor
aclass a;
//Create single object with constructor
aclass b(25);
//Create an array of objects which calls default
//constructor for each object
aclass an_array[3];
return 0;
}
"can u define objects in member functions?"
Sure, but it probably doesn't work the way you expect. First, the object is destroyed when the member function ends, and second to call the member function you need another object. Take a look at this code:
Code:
#include <iostream>
using namespace std;
class aclass
{
public:
aclass() //Default constructor
{
cout<<"Default constructor called."<<endl;
}
aclass(int n) //Constructor
{
cout<<"Constructor called."<<endl;
num = n;
}
void display()
{
cout<<"Data member num = "<<num<<endl;
}
void create()
{
aclass d(40);
d.display();
}
private:
int num;
};
int main()
{
aclass a;
a.create();
//d.display(); Uncomment this line-->error
return 0;
}
I don't know if you've studied this yet, but you can dynamically allocate memory for an object using the operator new and assign the address to a data member which is a pointer, and then you won't have the problem of the object being destroyed when the member function ends.
"also can u use a for loop or a do while loop in order to assign values to the array of objects?"
Sure, the compiler doesn't care what your object name is. Your object can be named my_object or my_array[1] and it doesn't matter. my_array is the name of the array of objects, but each object in the array has a name, and my_array[1] is the name of the second object in the array--my_array[0] is the name of the first.
Code:
#include <iostream>
using namespace std;
class aclass
{
public:
aclass() //Default constructor
{
cout<<"Default constructor called."<<endl;
}
aclass(int n) //Constructor
{
cout<<"Constructor called."<<endl;
num = n;
}
void display()
{
cout<<"Data member num = "<<num<<endl;
}
void set_num(int n)
{
num = n;
}
private:
int num;
};
int main()
{
aclass my_object;
aclass my_array[3];
my_object.set_num(25);
my_object.display();
my_array[0].set_num(40);
my_array[0].display();
return 0;
}