Suppose I have the following class in a header file
//tray.h

#include <vector>
#include "Eggs.h"
#ifndef TRAY_H
#define TRAY_H
class Tray{
    std::vector<Eggs> dozen;
    public:
        Tray();
        ~Tray();
        std::vector<Eggs> getTray() const;
};
#endif

And the following class file
//tray.cpp

#include "Tray.h"
#include <string>

Tray::Tray(){

}

Tray::~Tray(){

}

How do I initialize the vector dozen in the class?

Recommended Answers

All 2 Replies

You should use the initialization list, which is something like this in general:

Foo::Foo() : member1(/* something */), member2() { };

And so, for a dozen eggs, you should use one of the constructors of vector class, such as this:

Tray::Tray() : dozen(12, Eggs()) { };

where "Eggs()" can be some other constructor call, I just used the default constructor there.

And for the destructor, you don't need anything, because the vector will be automatically destroyed.

Just nitpicking, but this:

#include <vector>
#include "Eggs.h"
#ifndef TRAY_H
#define TRAY_H

should be this:

#ifndef TRAY_H
#define TRAY_H
#include <vector>
#include "Eggs.h"
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.