Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define class constructor outside class in another file?

Tags:

c++

So, I've got a class Car:

car.h

#ifndef CAR_H
#define CAR_H

#include <iostream>
#include <string.h>
#include "car.cpp"

// Car class with its attributes
class Car {
  public:
    std::string brand;   
    std::string model;
    int year;

    // Constructor
    Car(int year, std::string model, std::string brand);
};

#endif

and I wanted to make a class constructor definition outside the class in another .cpp file:

car.cpp

#include <string.h>

Car::Car(int year, std::string model, std::string brand)
{
  this->brand = brand;
  this->model = model;
  this->year = year;
}

I tried to compile, but this error has occurred:

car.cpp:3:1: error: ‘Car’ does not name a type

Why it happened and how to fix it?

My main.cpp:

#include <iostream>
#include "car.h"

using namespace std;

int main() {
  // Create an object of Car
  Car carObj1 = Car(1992, "model X", "Brand1");

  // Create another object of Car
  Car carObj2 = Car(2003, "model Y", "Brand2");

  // Print attribute values
  cout << carObj1.brand << " " << carObj1.model << " " << carObj1.year << "\n";
  cout << carObj2.brand << " " << carObj2.model << " " << carObj2.year << "\n";
  return 0;
}
like image 676
rebix Avatar asked Oct 21 '25 06:10

rebix


1 Answers

You got the includes the wrong way round. car.cpp should #include "car.h" not the other way around.

Also the correct header file for std::string is <string> not <string.h>

Also member initialisation is better done with initialiser lists not assignment

Car::Car(int year, std::string model, std::string brand) :
    brand(brand), model(model), year(year)
{
}
like image 88
john Avatar answered Oct 23 '25 21:10

john