First off I'm very new to c++. now what I cannot find anywhere is the ability to declare a variable of type class so that it can receive an object reference.
#include <iostream>
usingnamespace std;
class foo {
public:
int a;
foo ();
};
foo::foo() {
a = 231; // just a random number.
}
foo make_an_instance_foo(){
foo g;
return g;
}
int main(){
//foo f; works but I want the below to work too
f = make_an_instance_foo();
cout << f.a << endl;
system("PAUSE");
}
I know its a simple question but i cannot find anything on this. How would I declare f in 'f = make_an_instance_foo();' Please help thanks.
Ah, so you want to be able to create new foo variables on run-time? C++ directly provides a mechanism for that. It is called dynamic memory allocation and you can do it like this:
#include <iostream>
usingnamespace std;
class foo
{
public:
int a;
foo ();
};
foo::foo()
{
//just a random number.
a = 231;
}
int main()
{
//this is a foo pointer
foo * pfoo;
//create a new instance!
pfoo=new foo;
//access the foo instance
//through the foo pointer
cout << (*pfoo).a << endl;
//kill the instance
delete pfoo;
system("PAUSE");
return 0;
}
#include <iostream>
usingnamespace std;
class foo {
public:
int a;
foo ();
};
foo::foo() {
// just a random number.
a = 231;
}
foo make_an_instance_foo(){
foo g;
g.a = 999;
return g;
}
int main(){
// use f as foo referance?
foo f = make_an_instance_foo();
cout << f.a << endl;
system("PAUSE");
}
But does this mean that 2 instances are created(one of them being lost right away) or just 1?
But does this mean that 2 instances are created(one of them being lost right away) or just 1?
Good question. The answer is that 2 instances are created, one being g and one being f, and g is lost after being copied to f. Also, notice that this doesn't allocate memory on run-time. f is created on compile-time.
so Then to dynamically create and delete many instances of the same class during run-time I have to use pointer assignment ,to an array? otherwise they are lost or basically stuck in memory without a way to access them? Can making lots of instances be done with an array of references or just pointer's ( just for simplicity on the project I'm working on, references seem easier to handle. or rather easier to translate to)?
like: (not exactly sure how to make an array yet but just in general)
array fooArray(100) //but the array can be re-sized during run-time
for (int i = 0;i < 100; i++){
foo fooArray(i);
}