Use another class as member data - C++ Class

C++ examples for Class:Member Field

Description

Use another class as member data

Demo Code

#include <vector>
#include <cinttypes>
#include <iostream>

using namespace std;

class Wheel//from ww w.j  a  v  a2 s. c o  m
{

};

class Car
{
private:
    using Wheels = vector<Wheel>;
    Wheels m_Wheels;

public:
    void SetNumberOfWheels(int numberOfWheels)
    {
        m_Wheels.clear();
        for (int i = 0; i < numberOfWheels; ++i)
        {
            m_Wheels.push_back({});
        }
    }

    int GetNumberOfWheels()
    {
        return m_Wheels.size();
    }
};

int main(int argc, char* argv[])
{
    Car myCar;
    myCar.SetNumberOfWheels(4);

    cout << "Number of wheels: " << myCar.GetNumberOfWheels() << endl;

    Car myMotorcycle;
    myMotorcycle.SetNumberOfWheels(2);

    cout << "Number of wheels: " << myMotorcycle.GetNumberOfWheels() << endl;

    return 0;
}

Result


Related Tutorials