Definition of a class goes to header file, Student.h
class Student{
private: //access control
int ID;
string name;
public:
void setName(string n);
string getName();
void print();
};
private members can only be accessed within the classpublic members can be accessed within or outside the classIn Student.h:
class Student{
private:
int ID;
string name;
public:
Student(); //constructor
Student (int id);
Student (int id, string name); //constructor overloading
void setName(string n);
string getName();
void print();
}
We can dynamically allocate an object using a pointer
Student.cpp is the class implementation
#include "student.cpp"
#include <iostream>
void Student::setName(string n){ //setter function
name n; //private member of student class can be accessed inside the class implementation
}
string Student::getName(){ //getter function
return name;
}
void Student::print(){
count << "Student name: " << name;
cout << "Student ID: " << ID;
}
main.cpp is where we will use and instantiate the objects
#include "Student.h"
int main(){
Student x; //constructor called
Student y[10]; //constructor called 10 times
}
x.ID](<http://x.ID>)= 2730 since ID is a private memberID unless we use a constructorSolve this issue of memory leaks if you try to dynamically allocate an unknown amount of data in the main
new, you must use delete to free the memory and call the destructordelete//Student.h
class Student{
private:
int* grades;
public:
Student();
Student(int);
~Student(); //no return like constructors
}
//Class implementation
Student::~Student():
if(grades!= nullptr){
delete[] grades
}
}
class ComplexNum{
public:
double real;
double img;
ComplexNum(double r, double i){real = r, img = i};
};
int main(){
ComplexNum x(3,4);
x.real = 2;
ComplexNum* p; //pointer to ComplexNum
p = &x;
p-> real = 7;
//(*p).real =7
}