




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Three C++ program examples demonstrating the use of classes, constructors, destructors, methods, and object instantiation. The first example defines a Car class with a constructor, destructor, and a stop method. The second example defines a MyClass with constructors and a getx method. The third example defines an OLoading class with overloaded constructors and Payment methods. Each example includes the corresponding .h and .cpp files and a main function for testing.
Typology: Study notes
1 / 8
This page cannot be seen from the preview
Don't miss anything!





// Example 1 - Car.h //Define class Car //Interface for class Car #ifndef CAR_H #define CAR_H class Car { private: //optional – by default int numOfTyre; public: Car (int tyre); //Constructor ~Car (); //Destructor void stop(); //Metod }; #endif // Car.cpp //The definition of class interface in Car.h
using namespace std; //Contructor Car::Car (int tyre) { numOfTyre = tyre; } //Destructor Car::~Car() { } //Method stop void Car::stop() { cout << "Please stop now! " << numOfTyre << " tyre" << endl; } // CarMain.cpp
using namespace std; void main() { // Create and initialize 2 object Car Kembara (5); Car Kancil (4); //Call for method stop for Kembara object Kembara.stop (); //Call for method stop for Kancil object Kancil.stop();
// Oloading.h #ifndef OLOADING_H #define OLOADING_H class OLoading { private: double loan; public: OLoading(); //default constructor OLoading(double); //overloading constructor ~OLoading(); //destructor //overloading Payment 1 double Payment (int, double); //overloading Payment 2 double Payment (int, double, double); }; #endif // Oloading.cpp #include #include "OLoading.h" using namespace std; OLoading::OLoading() { loan = 10000; } OLoading::OLoading(double l) { loan = l; } OLoading::~OLoading() {} double OLoading::Payment(int month, double interest) { return (loan/month * interest); } double OLoading::Payment(int year, double interest, double deposit) { return (deposit - (loan / (12 * year) * interest) ); }
// Student.h #ifndef STUDENT_H #define STUDENT_H class Student { public: int metric; int yearOfStudy; Student (); //Constructor ~Student (); //Destructor void printData(); //Method }; #endif // Student.cpp
using namespace std; //Contructor definition Student::Student () { metric = 0; yearOfStudy = 0; } //Default Destructor Student::~Student() { } //printData method void Student::printData() { cout << "Metric Number : " << metric << endl; cout << "Year Of Study : " << yearOfStudy << endl; } // StudentMain.cpp
using namespace std; void main() { //Create Student object Student first; first.metric = 718; first.yearOfStudy = 1; //Call for method printData() first.printData(); }