0% found this document useful (0 votes)
31 views32 pages

4th - Week 5

Uploaded by

bdxqffcdq2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views32 pages

4th - Week 5

Uploaded by

bdxqffcdq2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Class Constructor

In C++, a constructor is a special member function that is used to


initialize the object's data members when the object is created. It
has the same name as the class and no return type.

The constructor is called automatically when an object of a class is


created, and it can be used to initialize data members to default
values, or to values passed as arguments. The constructor can also
be overloaded with different argument lists to provide flexibility in
object initialization.

To create a constructor, use the same name as the class, followed


by parentheses ():
Class Constructor
#include <iostream>
using namespace std;

class MyClass { // The class


public: // Access specifier
MyClass() { // Constructor
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass (this will
call the constructor)
return 0;
}
Class Constructor

Constructors can also take parameters (just like regular functions),


which can be useful for setting initial values for attributes.

The following class have brand, model and year attributes, and a
constructor with different parameters. Inside the constructor we set
the attributes equal to the constructor parameters (brand=x, etc).
When we call the constructor (by creating an object of the class), we
pass parameters to the constructor, which will set the value of the
corresponding attributes to the same:
Class Constructor
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z) { // Constructor with parameters
brand = x;
model = y;
year = z;
}
};

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
Class Constructor
#include <iostream>
#include <string>
using namespace std;
class Car {
public:
// Constructor definition
Car(string brand, string model, int year) {
this->brand = brand;
this->model = model;
this->year = year;
}
// Function to print car information
void describe() {
cout << brand << " " << model << " " << year << endl;
}
private:
string brand;
string model;
int year;
};
int main() {
// Constructor is automatically called when an instance of Car is created
Car car1("Toyota", "Corolla", 2020);
// Printing car information
car1.describe(); // Output: Toyota Corolla 2020
return 0;
}
Class Methods

Constructors can also be defined outside the class. First, declare the
constructor inside the class, and then define it outside of the class by
specifying the name of the class, followed by the scope resolution ::
operator, followed by the name of the constructor (which is the same
as the class):
class Car { // The class
public: // Access specifier
string brand; // Attribute
string model; // Attribute
int year; // Attribute
Car(string x, string y, int z); // Constructor declaration
};

// Constructor definition outside the class


Car::Car(string x, string y, int z) {
brand = x;
model = y;
year = z;
}

int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);

// Print values
cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
return 0;
}
#include <iostream>
#include <string>
using namespace std;
class Fruit {
public:
// Constructor declaration
Fruit(string name, string color);
// Function to describe fruit
void describe();
private:
string name;
string color;
};
// Constructor definition outside the class declaration
Fruit::Fruit(string name, string color) {
this->name = name;
this->color = color;
}
// Function definition to describe fruit
void Fruit::describe() {
cout << "Name: " << name << ", Color: " << color << endl;
}
int main() {
// Creating an instance of the Fruit class
Fruit apple("Apple", "Red");
// Describing the fruit
apple.describe(); // Output: Name: Apple, Color: Red
return 0;}
Class Methods

Methods are functions that belongs to the class. There are two ways
to define functions that belongs to a class:Inside / Outside class

To define a function inside the class definition


Class Methods
class MyClass { // The class
public: // Access specifier
void myMethod() { // Method/function defined inside the class
cout << "Hello World!";
}
};

int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
#include <iostream>
Class Methods
using namespace std;

class MyClass {
private:
int myVar;
public:
MyClass(int x) {
myVar = x;
}
int getMyVar() {
return myVar;
}
};

void myFunction() {
cout << "Hello, world!" << endl;
}

int main() {
MyClass obj(42);
cout << "My variable is: " << obj.getMyVar() << endl;
myFunction();
return 0;
}
Class Methods
This program defines a class called MyClass with a private member
variable called myVar and a public constructor that takes an integer
argument and sets myVar to that value. It also defines a public
member function called getMyVar that returns the value of myVar.

The program also includes a function called myFunction that simply


prints out "Hello, world!" to the console.

Finally, the main function creates an instance of MyClass, calls its


getMyVar function to retrieve the value of myVar, and prints it to the
console. It also calls myFunction to print out the "Hello, world!"
message.
#include <iostream>
#include <string>
Class Methods
using namespace std;
class Student {
public:
Student(string name, int age, string major); // Constructor declaration
void setGPA(double gpa); // Function to set the GPA
void printInfo(); // Function to print student information
private:
string name;
int age;
string major;
double gpa;};
// Constructor definition
Student::Student(string name, int age, string major) {
this->name = name;
this->age = age;
this->major = major;
this->gpa = 0.0; // Initializing GPA to 0
}
// Function to set the GPA
void Student::setGPA(double gpa) {
this->gpa = gpa;
}
Class Methods

// Function to print student information


void Student::printInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Major: " << major << endl;
cout << "GPA: " << gpa << endl;}

int main()
{
Student student1("John Doe", 20, "Computer Science"); // Creating an instance of the
Student class
student1.setGPA(3.5); // Setting the GPA
student1.printInfo(); // Printing student information
return 0;
}
Class Methods

To define a function outside the class definition, you have to declare it


inside the class and then define it outside of the class. This is done by
specifiying the name of the class, followed the scope resolution ::
operator, followed by the name of the function:
Class Methods

class MyClass { // The class


public: // Access specifier
void myMethod(); // Method/function declaration
};
// Method/function definition outside the class
void MyClass::myMethod() {
cout << "Hello World!";
}
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
#include <iostream>
using namespace std;
Class Methods
class MyClass {
private:
int myVar;
public:
MyClass(int x);
int getMyVar();
};

MyClass::MyClass(int x) {
myVar = x;
}

int MyClass::getMyVar() {
return myVar;
}

void myFunction() {
cout << "Hello, world!" << endl;
}

int main() {
MyClass obj(42);
cout << "My variable is: " << obj.getMyVar() << endl;
myFunction();
return 0;
}
Class Methods

This program is similar to the previous one, but the constructor


and getMyVar function are defined outside the class definition
using the scope resolution operator ::. Additionally, it defines a
function called myFunction outside the class definition, which is
called from main.

Note that the class definition still includes the declarations for the
constructor and getMyVar function, but their definitions are
moved outside the class definition. This is a common pattern in C+
+ programming, where larger classes may have many member
functions that are best defined outside the class definition to
improve code organization and readability.
Class Methods
Parameters
You can also add parameters:
#include <iostream>
using namespace std;
class Car {
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {


return maxSpeed;
}

int main() {
Car myObj; // Create an object of Car
cout << myObj.speed(200); // Call the method with an argument
return 0;
}
Access Specifiers

There are three access specifiers:


public - members are accessible from outside the class
private - members cannot be accessed (or viewed) from
outside the class
protected - members cannot be accessed from outside the
class, however, they can be accessed in inherited classes.
You will learn more about Inheritance later.
Access Specifiers
class MyClass {
public: // Public access specifier
int x; // Public attribute
private: // Private access specifier
int y; // Private attribute
};

int main() {
MyClass myObj;
myObj.x = 25; // Allowed (public)
myObj.y = 50; // Not allowed (private)
return 0;
}
Access Specifiers

By default, all members of a class are private if you don't specify


an access specifier:

class MyClass {
int x; // Private attribute
int y; // Private attribute
};
Access Specifiers

The private keyword is used to specify the access level of a class


member. When a class member is declared as private, it can only
be accessed from within the class itself. This means that any code
outside of the class cannot directly access or modify the private
member.
Access Specifiers

The primary purpose of making a member private is to


encapsulate the implementation details of the class. By hiding the
details of how the class works from other parts of the program,
we can prevent accidental or intentional modification of the
class's internal state, ensuring that the class remains in a valid
state at all times. This is especially important for larger, more
complex classes, where it can be difficult to keep track of all the
interactions between different parts of the program.
#include <iostream> Access Specifiers
class MyClass {
private:
int privateNum;

public:
void setNum(int num) {
privateNum = num;
}

void printNum() {
std::cout << "Private number is: " <<
privateNum << std::endl;
}
};

int main() {
MyClass myObj;
myObj.setNum(42);
myObj.printNum();
return 0;
}
Access Specifiers

In this example, the MyClass class has a private member variable


privateNum, which can only be accessed within the class itself. The
setNum() method is a public member function that allows us to set
the value of privateNum, and the printNum() method is another
public member function that allows us to print the value of
privateNum.

When we create an instance of the MyClass class in the main()


function, we can use the setNum() method to set the value of
privateNum, and then use the printNum() method to print it out.
Because privateNum is a private member, we cannot access it
directly outside of the class.
#include <iostream>
#include <string>
Class Methods
using namespace std;
class Student {
public:
Student(string name, int age, string major); // Constructor declaration
void setGPA(double gpa); // Function to set the GPA
void printInfo(); // Function to print student information
private:
string name;
int age;
string major;
double gpa;};
// Constructor definition
Student::Student(string name, int age, string major) {
this->name = name;
this->age = age;
this->major = major;
this->gpa = 0.0; // Initializing GPA to 0
}
// Function to set the GPA
void Student::setGPA(double gpa) {
this->gpa = gpa;
}
Access Specifiers

The protected keyword is another access specifier that can be


used to control access to class members. Like private, protected is
used to specify the visibility of a class member within the class
itself. However, there is one key difference: protected members
can also be accessed by derived classes.
Access Specifiers

The primary purpose of making a member protected is to allow


derived classes to access and modify the state of the base class.
This can be useful in cases where we want to provide a base
implementation that can be customized by derived classes. For
example, we might have a base class Animal with a protected
member age, and then derive a Dog class from it that provides its
own implementation of the bark() method, based on the animal's
age.
Access Specifiers
#include <iostream>

class Animal {
protected:
int age;
public:
Animal(int a) : age(a) {}

virtual void speak() {


std::cout << "Animal speaks" << std::endl;
}
};
class Dog : public Animal {
public:
Dog(int a) : Animal(a) {}

void bark() {
std::cout << "Woof! I am " << age << " years old." << std::endl;
}
};
int main() {
Dog myDog(3);
myDog.bark();
myDog.speak();
return 0;
}
#include <iostream>
#include <string> Access Specifiers
using namespace std;

class Student {
public:
Student(string name, int age, string major); // Constructor declaration
void setGPA(double gpa); // Function to set the GPA
void printInfo(); // Function to print student information

protected:
string name;
int age;
string major;
double gpa;
};

// Constructor definition
Student::Student(string name, int age, string major) {
this->name = name;
this->age = age;
this->major = major;
this->gpa = 0.0; // Initializing GPA to 0
}
// Function to set the GPA Access Specifiers
void Student::setGPA(double gpa) {
this->gpa = gpa;
}

// Function to print student information


void Student::printInfo() {
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Major: " << major << endl;
cout << "GPA: " << gpa << endl;
}

int main() {
Student student1("John Doe", 20, "Computer Science"); // Creating an instance of the
Student class
student1.setGPA(3.5); // Setting the GPA
student1.printInfo(); // Printing student information
return 0;
}

You might also like