C++ Arrays: Example
C++ Arrays: Example
To declare an array, define the variable type, specify the name of the
array followed by square brackets and specify the number of elements it
should store:
string cars[4];
int myNum[3] = {10, 20, 30};
Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Example
cars[0] = "Opel";
Example
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
cout << cars[0];
// Now outputs Opel instead of Volvo
Example
The following example outputs the index of each element together with its
value:
Example
This is completely fine. However, the problem arise if you want extra
space for future elements. Then you have to overwrite the existing values:
If you specify the size however, the array will reserve the extra space:
string cars[5] = {"Volvo", "BMW", "Ford"}; // size of array is 5, even
though it's only three elements inside it
Now you can add a fourth and fifth element without overwriting the
others:
cars[3] = "Mazda";
cars[4] = "Tesla";
Try it Yourself »
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
...
Creating Pointers
You learned from the previous chapter, that we can get the memory
address of a variable by using the & operator:
Example
Try it Yourself »
Try it Yourself »
Example explained
Create a pointer variable with the name ptr, that points
to a string variable, by using the asterisk sign * (string* ptr). Note
that the type of the pointer has to match the type of the variable you're
working with.
Tip: There are three ways to declare pointer variables, but the first way is
preferred:
Try it Yourself »
Note that the * sign can be confusing here, as it does two different things in our
code:
Example
// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The
car has attributes, such as weight and color, and methods, such as
drive and brake.
A class is a user-defined data type that we can use in our program, and it
works as an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
Example
Example explained
Create an Object
In C++, an object is created from a class. We have already created the
class named MyClass, so now we can use this to create objects.
Example
int main() {
MyClass myObj; // Create an object of MyClass
Multiple Objects
You can create multiple objects of one class:
Example
int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;
Class Methods
Methods are functions that belongs to the class.
Inside Example
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Try it Yourself »
Outside Example
int main() {
MyClass myObj; // Create an object of MyClass
myObj.myMethod(); // Call the method
return 0;
}
Try it Yourself »
Parameters
You can also add parameters:
Example
#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;
}
Constructors
A constructor in C++ is a special method that is automatically called
when an object of a class is created.
Example
Try it Yourself »
Note: The constructor has the same name as the class, it is always public, and it
does not have any return value.
Constructor Parameters
Constructors can also take parameters (just like regular functions), which
can be useful for setting initial values for attributes.
Example
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;
}
Try it Yourself »
Just like functions, 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):
Example
int main() {
// Create Car objects and call the constructor with different values
Car carObj1("BMW", "X5", 1999);
Car carObj2("Ford", "Mustang", 1969);
Access Specifiers
By now, you are quite familiar with the public keyword that appears in all
of our class examples:
Example
Try it Yourself »
Example
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;
}
error: y is private
Try it Yourself »
Tip: It is considered good practice to declare your class attributes as private (as
often as you can). This will reduce the possibility of yourself (or others) to mess up
the code. This is also the main ingredient of the Encapsulation concept, which you
will learn more about in the next chapter.
Example
class MyClass {
int x; // Private attribute
int y; // Private attribute
};
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is
hidden from users. To achieve this, you must declare class
variables/attributes as private (cannot be accessed from outside the
class). If you want others to read or modify the value of a private
member, you can provide public get and set methods.
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
}
Try it Yourself »
Example explained
The salary attribute is private, which have restricted access.
Why Encapsulation?
It is considered good practice to declare your class attributes as
private (as often as you can). Encapsulation ensures better control
of your data, because you (or others) can change one part of the
code without affecting other parts
Increased security of data
Inheritance
In C++, it is possible to inherit attributes and methods from one class to
another. We group the "inheritance concept" into two categories:
Example
// Base class
class Vehicle {
public:
string brand = "Ford";
void honk() {
cout << "Tuut, tuut! \n" ;
}
};
// Derived class
class Car: public Vehicle {
public:
string model = "Mustang";
};
int main() {
Car myCar;
myCar.honk();
cout << myCar.brand + " " + myCar.model;
return 0;
}
Try it Yourself »
Multilevel Inheritance
A class can also be derived from one class, which is already derived from
another class.
Example
int main() {
MyGrandChild myObj;
myObj.myFunction();
return 0;
}