3

I am learning c++. I am tring to make a couple of objects inside another object but compiler is giving error - no matching function for call to 'Grass::Grass()' .

This is the header file of "world" object. In it I declared two "grass" 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 make the "grass" objects but failed.

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

using namespace std;

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

1 Answer 1

3

Your syntax is wrong. You're looking for what's known as a constructor initialization list. Try (assuming you've got the signature for the Grass constructor correct):

World::World() : 
    g1(200, 200),
    g2(300, 200)
{
    // Nothing 
} 
Sign up to request clarification or add additional context in comments.

2 Comments

The constructor initialization list can be used for any member variable that requires construction upon initialization including primitive types.
@Andy and it should always be used if possible, even if the type has a default constructor, since instead of two calls (ctor + assignment operator) you only call the copy/move ctor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.