+ 1
can anyone tell me an example of constructor with definition in easy words
4 ответов
+ 5
Each class you declare can provide a constructor that can be used to initialize an object of the class when the object is created.
A constructor is a special member function that must be defined with the same name as the class.
Constructors cannot return value, so they cannot specify a return type - not even void.
Normally, constructors are declared public.
class a
{
public:
a(int value= 0)// constructor
: x( value )
{ }
...
private:
int x;
};
int main(){
a obj1(7); // initializes 7 to obj1's x data member and overrides default value.
...
}
+ 5
Constructors are like car factories , make the factory once then make as many cars as you want from it , each car having the feature to move and do other things .
Same in coding write the method once and make objects again and again
-------------
Eg.
Consider you are making a game , If I make a constructor Rect which draws a rectangle on the screen at random position with function which moves the rectangle in circular motion.
Now we can recreate (construct)those rectangles again and again just by calling the Rect constructor
r1=new Rect();
r1.move();
r2=new Rect();
r2.move();
it will create two rectangles at random positions each moving independently .
We can use for loops and arrays to construct them as many times as we want without writing all this .
The point is making self sufficient objects each having their own functions by writing the code once .
+ 1
oh now I got it
the examples were really helpful
thanks to all