irappa
irappa

Reputation: 749

Accessing nested class in C++

I came across this question in an online test that I was taking. The task is to alter this program to get rid of compilation errors.

#include<iostream>
#include<iomanip>

class Vehicle
{
public:
    static Car* createCar()
    {
        return new Car;
    }

    class Car
    {
        public:
            string name;
    };
private:
    int seats;
};

void useVehicle()
{
    Vehicle::Car *c = Vehicle::createCar();
    c->name = "BMW";
}

int main(int argc, char *argv[])
{
    useVehicle();
    return 0;
}

The compilations errors are like:
error: ‘Car’ does not name a type
error: ‘string’ does not name a type
In function void useVehicle():
error: ‘createCar’ is not a member of ‘Vehicle’

How do I get it right ? I tried few things but could not resolve these errors.

Upvotes: 1

Views: 145

Answers (1)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132984

error: ‘Car’ does not name a type

At the point of

static Car* createCar()

Car is not yet known. Move the definition of class Car above the function

error: ‘string’ does not name a type In function ‘void useVehicle()’:

#include <string>

also use std:: to qualify string

error: ‘createCar’ is not a member of ‘Vehicle’

This error will disappear once you fix the other two issues. The compiler wasn't able to parse the function declaration because it didn't know what its return type was.

Upvotes: 6

Related Questions