In: Computer Science
Lab11B:Understanding the constructor. Remember that the constructor is just a special method (with no return type) that has the same name as the class name. Its job is to initialize all of the attributes. You can actually have more than one constructor, so long as the parameters are different. Create a class called Turtle that has two attributes: 1) speed and 2) color. Then, create a constructor that has no parameters, setting the default speed to 0 and the color to “green”; this is called a default constructor.Next, create a second constructor that takes in two parameters. The second constructor should assign those parameters to the attributes. Then, in main, create two Turtle objects. For the first Turtle object, call the first constructor. For the second Turtle object, call the second constructor (passing it a speed of 5 and a color of “purple”). Using the dot ‘.’ Operator, print out the first turtle’s speed and the second turtle’s color.This is a test to see if you can design constructors inside your class and initialize attributes.
Sample output #1
0
purple
#include <iostream>
using namespace std;
class Turtle
{
public:
double speed;
string color;
Turtle()
{
speed=0;
color="green";
}
Turtle(string col, double sp)
{
color=col;
speed=sp;
}
};
int main()
{
Turtle t1;
cout<<t1.speed<<endl;
Turtle t2=Turtle("purple",5);
cout<<t2.color;
}
I hope it helps.