Calling Constructor conditionally

  • Thread starter Thread starter Karthik D V
  • Start date Start date
K

Karthik D V

Is there any way to call the base class constructor conditionally.

For Example

class Shape
{
public Shape(int x)
{

}
}

class Rectangle : Shape
{
Shape(int x, int y) : base(x)
{

}
}

This works fine...

But what if i need something like this ??

class Rectangle : Shape
{
Shape(int x, int y)
{
if( x > y) //Some condition
{
// How Do I pass x value to base class here.?
}
}
}

As for as i know this is not possible. Am I right here????
 
You can either create an initialization method that you call from the
constructor, or you can do the following:

class Base
{
public Base(int x)
{
}
}

class Derived : Base
{
public Derived(int x, int y)
: base((x < y) ? x : y)
{
}
}

Mark
 
Hi Mark R. Dawson,

If condition doesn't satisfies , i dont want to call the base
class constructor.

Well thanks for reply.
 
Karthik D V said:
If condition doesn't satisfies , i dont want to call the base
class constructor.

You can't do that. You'd have to have a static method which determined
what you wanted to do, and then called one of a range of Derived class
constructors which did the appropriate thing.
 
Back
Top