returning a subclass type object

I have a problem in returning the object of subclasses.
Here is my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
typedef /*what will I put here*/ SetGeneratedBlock(int bGen)
{
	const int BLOCKL = 1, BLOCKZ = 2, BLOCKS = 3, BLOCKT = 4, BLOCKI = 5;
	CShapeL lshape;
	CShapeZ zshape;
	CShapeS sshape;
	CShapeT tshape;
	CShapeI ishape;

	switch(bGen){
		case BLOCKL:
			return lshape;
		case BLOCKZ:
			return zshape;
		case BLOCKS:
			return sshape;
		case BLOCKT:
			return tshape;
		case BLOCKI:
			return ishape;
	}
}


there are 5 subclasses of the baseclass CShape..
and I want to return the object of a specific subclass that were chosen..

So what is the proper way of doing this?

Thanks.
u can return the base class pointer itself from this function, and u can do dynamic cast to get the derived class pointer.
Hmm...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int main(){
    ....
    ....
	CGraphics draw;//creates an object of CGraphics class
	CShape cBlock;//creates an object of CShape class
	draw.drawBorder();//draws a blue border
	draw.printText();
	cBlock.assignBorderValues();
//	openingSound();
	genBlock = generateBlock();//generate random blocks
        //is this declaration wrong?
	CShape * chosenBlock = &(cBlock.SetGeneratedBlock(genBlock));

}

I only copy the syntax from an example in a book
1
2
3
4
CRectangle rect;
CTriangle trgl;
CPolygon * ppoly1 = &rect;//<---I copied this syntax, since the return value of my code is
CPolygon * ppoly2 = &trgl;//       an object of a subclass. 
It is not possible to create the derived object using Base class object.

That's why I have this declaration in my function...

1
2
3
4
5
6
7
8
9
10
11
typedef /*what will I put here*/ SetGeneratedBlock(int bGen)
{
	const int BLOCKL = 1, BLOCKZ = 2, BLOCKS = 3, BLOCKT = 4, BLOCKI = 5;
	CShapeL lshape; //<--I create the derived object first then I pass the value to main function
	CShapeZ zshape;
	CShapeS sshape;
	CShapeT tshape;
	CShapeI ishape;
        ...
        ...
}
Topic archived. No new replies allowed.