constructors

This commit is contained in:
2020-05-10 16:07:27 +02:00
parent d6f2d44eaf
commit b9c03f8207
15 changed files with 257 additions and 1 deletions

View File

@ -0,0 +1,6 @@
# Constructors in C++
## Relevant files
- [car.h](./car.h)
- [car.cpp](./car.cpp)

23
cpp/constructors/car.cpp Normal file
View File

@ -0,0 +1,23 @@
// include the header file
#include "car.h"
// include necessary libraries and namespaces
#include <iostream>
#include <string>
using namespace std;
// define the implementation for car.print_info()
void car::print_info()
{
cout << "Car Information:" << endl;
// fields that are defined in the header file can just be used like normal variables here
cout << "- manufacturer: " << manufacturer << endl;
cout << "- model: " << model << endl;
}
car::car(string manufacturer, string model) {
// set manufacturer of the current object to the given manufacturer
this->manufacturer = manufacturer;
// set model of the current object to the given model
this->model = model;
}

22
cpp/constructors/car.h Normal file
View File

@ -0,0 +1,22 @@
#pragma once
// including a necessary library and namespace to work with strings
#include <string>
using namespace std;
// define the class
class car
{
private:
// define two fields, manufacturer and model
// this time as private to make the data only settable through the constructor or other local functions
std::string manufacturer;
std::string model;
public:
// define the constructor, taking manufacturer and model as parameters
car(std::string manufacturer, std::string model);
// define a method that will print out information
void print_info();
};

15
cpp/constructors/main.cpp Normal file
View File

@ -0,0 +1,15 @@
#include "car.h"
#include <cstring>
int main() {
// create a new car and store it in the variable 'a'
// The constructor requires manufacturer and model to be specified.
car a("Benz", "Velo");
// do the same for a second car
car b("Ford", "Model T");
// use a function of the car class to print out the information
a.print_info();
b.print_info();
}