How do I declare and create objects inside another object constructor?

I am learning C ++. I'm trying to make a couple of objects inside another object, but the compiler gives an error - there is no corresponding function to call "Grass :: Grass ()" .

This is the header file for the "world" object. In it, I have declared two "herbal" objects: -

#ifndef WORLD_H
#define WORLD_H
#include "Grass.h"

using namespace std;

class World
{
public:
World();

private:
Grass g1;
Grass g2;
};

      

This is the cpp file of the "world" object. In the constructor, I tried to create grass objects, but I couldn't.

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

using namespace std;

World::World()
{
g1(200, 200);
g2(300, 200);
} 

      

+3


source to share


1 answer


Your syntax is incorrect. You are looking for what is known as a constructor initialization list. Try (if you have a signature for the constructor Grass

):



World::World() : 
    g1(200, 200),
    g2(300, 200)
{
    // Nothing 
} 

      

+3


source







All Articles