OOP Ch 3-Constructor.docx.pdf

Full Transcript

Unit 3 Constructors & Destructors C++ Constructor A constructor in C++ is a special method that is automatically called when an object of a class is created. It is used to initialize the data members of new object generally. The const...

Unit 3 Constructors & Destructors C++ Constructor A constructor in C++ is a special method that is automatically called when an object of a class is created. It is used to initialize the data members of new object generally. The constructor in C++ has the same name as class or structure. Syntax: class class_name { // data members; // member functions; public: class_name() //constructor { //body of constructor } //member functions; }; Eg: class Time { int hr; int min; public: Time() // Constructor { hr=0; min=0; } }; To create a constructor, use the same name as the class, followed by parentheses (): Example : class MyClass { public: MyClass() { cout

Use Quizgecko on...
Browser
Browser