-
Constructor
can i pass parameters into the initial constructor or do i have to use another one
class blabla
{
blabla(//some parameters here??)
blabla(//or in this one if i want)
~blabla()
//and so on
}
i kno i can overload the constructor but can the initial one take parameters
was writing a fair size program using structs and then stumbled across these (might as well start over because classes are the answer)
classes rock
-
Yes you can!
Code:
class Test
{
public:
int iValue;
Test(); // Default
Test( int iTemp ); // Alternate
~Test();
};
Test::Test()
{
iValue = 0;
}
Test::Test( int iTemp )
{
iValue = iTemp;
}
Test::~Test()
{
}
int main()
{
Test Class1; // Uses default constructor, iValue is 0;
Test Class2( 50 ); // Use alternate constructor, iValue is 50.
return 0;
}
-
so is it like this:
class blabla
{
//all default parameters declared here
blabla()
blabla(//or in this one if i want)
~blabla()
//and so on
}
-
>can i pass parameters into the initial constructor
Every class has a default constructor that takes no arguments, you can then overload the constructor to do whatever you want in different situations.
Code:
class Fooby
{
int data;
public:
// Must have a default, but you don't have to define it
Fooby();
// You can also overload
Fooby ( int input );
};
// Fooby class fleshy
Fooby :: Fooby() : data ( 10 )
{
// data is set to a default value of 10
}
Fooby :: Fooby ( int input ) : data ( input )
{
// data is set to user input
}
The default constructor is just that, you don't HAVE to have it in your code because the class will generate it for you. If you want something specific to be done in the constructor then you will either have to define the default or overload.
-Prelude
-
Can you do this?
class Fooby
{
int data;
double data2;
public:
Fooby();
Fooby ( int input );
Fooby (double input);
};
-
>Can you do this?
Yes, the compiler determines which overloaded function to use based on the type and number of arguments, so two overloaded constructors with one argument each but of different types is quite legal.
-Prelude
-
Yes, that's a type of polymorphism. (For constructors)
Code:
class Object {
public:
Object();
Object(double t);
Object(char* t);
~Object();
};
Depending on the arguments passed, the compiler will choose the appropriate function from it's look-up list.