PDA

View Full Version : experienced c++ people help?



sherlockmeister
04-08-2008, 10:54 PM
i feel a little bit stupid asking this but oh well...
is there any better way to init a class in a class declared before it other than like this:



class two;
two*init();
class one{
void nothing(){
init();
}
};
class two{
};
two*init(){
return new two;
}

i'm pretty sure there isn't which is why i feel stupid asking..but just making sure

R0b0t1
04-09-2008, 09:57 PM
What? Maybe better indentation is in order...?

You mean something like:



class one; //Not sure if you can forward classes

class two
{
//stuff here
};

class one
{
//stuff here
two init;
};

two one::init()
{
return new two;
}


used as



one Classone;

ClassContainer = (two)Classone.init;



????????


If thats what you want to do there is a better way.

sherlockmeister
04-13-2008, 12:39 AM
this is basically what i was trying to achieve:
two classes that are able to use each other even though one is after the other,
actually the answer was easier than i thought.

what i was doing first:

class one{
void something(){
two t;
}
}

class two{
void something(){
one o;
}
}

you cant do this because class 'one' is not defined...however one can simply do this:

class one{
void something();
};

class two{
void something();
};

void one::something(){
two t;
}

void two::something(){
one o;
}

somethings you just take for granted in java...

boberman
04-17-2008, 03:12 PM
this is basically what i was trying to achieve:
two classes that are able to use each other even though one is after the other,
actually the answer was easier than i thought.

what i was doing first:

class one{
void something(){
two t;
}
}

class two{
void something(){
one o;
}
}

you cant do this because class 'one' is not defined...however one can simply do this:

class one{
void something();
};

class two{
void something();
};

void one::something(){
two t;
}

void two::something(){
one o;
}

somethings you just take for granted in java...

So wait, if I am understanding this correctly there is data in one that you want in two and data in two that you want in one, correct? You might want to rethink your structure then and consider polymorphism and inheritance (IE a 3rd base class). So it looks something like this



#include <iostream>

using namespace std;

class base
{
protected:
int data;
public:
base()
{
data = 0;
}
virtual void function()
{
cout << "test" << data;
}
}
class one : public base
{
public:
one()
{
data = 1;
}
void function()
{
cout << "one" << data;
}
}
class two : public base
{
public:
two()
{
data = 2;
}
void function()
{
cout << "two " << data;
}
}
int main()
{
base* things[3];
thing[0] = new base;
thing[1] = new one;
thing[2] = new two;
for(int i = 0; i < 3; ++i)
{
things[i]->fucntion();
cout << endl;
delete things[i];
things[i] = null;
}
}


Give er a whiral to see polymorphism and inheritance in action.