error const

Why doesn't it work when I put "const" on the line 7 of my Car.h header. but work when i don;t put it?
i says that i should put the function as a constant

error message :
1
2
3
error: member function 'getType' not viable: 'this' argument has type 'const Car', but function is not const:
os<<car.Car::getType()<<" --> "<<car.Car::getPrice();
	os<<" - "; 

Car.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Car{
	public:
	Car(const std::string& type, double price);
	Car();
		
	std::string getType();
	double getPrice();
		
 =====> friend std::ostream& operator<< (std::ostream& os, const Car& car);
	
	private:
        std::string type;
	double price;

};

Car.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Car::Car(const std::string& typeCar, double priceCar){
	price = priceCar;
	type = typeCar;
}; 

Car::Car(){
	type = "Empty";
	price = 0;
};

std::string Car::getType(){
	return type;
}

double Car::getPrice(){
	return price;
}
std::ostream& operator<< (std::ostream& os,  const Car& car){
	os<<" - ";
		os<<car.Car::getType()<<" --> "<<car.Car::getPrice();
	os<<" - ";
	os<<std::endl;
	return os;
}


How can i make my "getType" function as const???
Last edited on
closed account (E0p9LyTq)
You have two problems with the code you posted.

1. You are declaring your class name as "Item" in your header file, yet your definitions as the class name is "Car."

2. Simply adding "const" to a method's declaration in the header file won't work, you need to add it to the method's definition as well:

car.h:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>

class Car
{
public:
   Car(const std::string& type, const double price);
   Car();

public:
   std::string getType() const;
   double getPrice() const;

   friend std::ostream& operator<< (std::ostream& os, const Car& car);

private:
   std::string type;
   double price;
};


car.cpp:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "car.hpp"

Car::Car(const std::string& typeCar, const double priceCar)
{
   price = priceCar;
   type = typeCar;
}

Car::Car()
{
   type = "Empty";
   price = 0;
}

std::string Car::getType() const
{
   return type;
}

double Car::getPrice() const
{
   return price;
}

std::ostream& operator<< (std::ostream& os, const Car& car)
{
   os <<  " - ";
   os << car.Car::getType() << " --> " << car.Car::getPrice();
   os << " - \n";
   return os;
}

The Item thing was from a previous exercise. sorry for that

However. I didn't take in consideration the fact that all the other variable should take const. i forgot about that .
thank you
Topic archived. No new replies allowed.