Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

classes constructor in c++

//constructor
//carrys the same name of the class
//it is neither void nor return
//is called during the declaration of object

class Triangle {
private:
	float base;
	float height;
public:
	//constructor
	//Type 1(empty constructor,without parameters nor arguments)
	Triangle() {
		cout << "First constructor
";
		height = base = 0;					//gives initial value to the class members
	}

	//Type 2(parameterized constructor)
	Triangle(float b, float h) {
		cout << "parameterized constructor
";
		base = b;
		height = h;
	}
  
  	//default constructor
	Student(float b, float h = 5) {
		cout << "Default parameterized constructor
";
		base = b;
		height = h;
    }

  //print function
  void print() {
		cout << "Base= " << getBase() << endl;
		cout << "Height= " << getHeight() << endl;
	}
};

int main() {
  // triangle will call empty Constructor
	Triangle triangle;
  	triangle.print();
  
  // triangle2 will call parameterized Constructor
	Triangle triangle2;
  	triangle2.print();
  
   // triangle3 will call default parameterized Constructor
	Triangle triangle3(2);
  	triangle3.print();


}
 
PREVIOUS NEXT
Tagged: #classes #constructor
ADD COMMENT
Topic
Name
3+8 =