Hi all, the search function failed to yield any results for me so I come here to create a new thread. I'm learning C++ on my own (sort of a weird hobby of mine to learn code, don't ask) and had an interesting question...

Consider the following:

Ingredients.h

#ifndef RECIPE_H
#define RECIPE_H

class Recipe
{
};

#endif

and...
Recipe Manager.cpp

#include "stdafx.h"
#include <iostream>
#include <string>
#include "Recipe.h"

int main()
{
}

inside of my main function in "Recipe Manager.cpp" would I somehow be able to accept a std::cin to create a new object of my Recipe class? For instance, would something like the following work:

string title = "";
std::cin >> title;
Recipe title;

I get that in line #3 above, a new object of Recipe will be instantiated with the name of "title", but what I'm looking for is a way for std::cin to create a new object of Recipe with the name of what the user types... is this possible?

Some background on me: pretty good at Java, learning C++ through "www.learncpp.com" currently at mid-chapter 8. Not in school yet, so you don't have to worry about me cheating on homework...

All help is appreciated, thank you.

Recommended Answers

All 3 Replies

No, this is not possible and even not meaningful. Why would you want a program user to specify the name of a variable?
If you want to give a name to your "Recipe", all you need is to give it an attribute (i.e. a member variable) which you can set when creating a new object (Recipe). You could do this by initializing it in the constructor.

#ifndef RECIPE_H
#define RECIPE_H
class Recipe
{
public:
  Recipe(const string t) : sTitle(t) {};
private:
  string sTitle;
};
#endif

and than in your main function you could do:

string title = "";

std::cin >> title;

Recipe someCake(title);

Now you have a Recipe with a title.

Best regards

<Sorry, misunderstood the question.>

No, this is not possible and even not meaningful. Why would you want a program user to specify the name of a variable?
If you want to give a name to your "Recipe", all you need is to give it an attribute (i.e. a member variable) which you can set when creating a new object (Recipe). You could do this by initializing it in the constructor.

#ifndef RECIPE_H
#define RECIPE_H
class Recipe
{
public:
  Recipe(const string t) : sTitle(t) {};
private:
  string sTitle;
};
#endif

and than in your main function you could do:

string title = "";

std::cin >> title;

Recipe someCake(title);

Now you have a Recipe with a title.

Best regards

Thanks a ton, it always helps to have another mindset with this stuff. I'll play around with what you suggested and try to see if I can get that to work for me. Thanks for the help.

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.