Returning Objects

Hi, im new on OOP paradigm. Im trying to do I/O Modules for strings, and other for a stack ADT. My idea is to create an empty object, call the Input instruction, and return it filled, like this:

1
2
  std::string string;
string = Input(string);


And the same goes for the stack ADT.

Is this correct? Is there any better way to do it?

PS: This is my first time writting so "technically" in English, so sorry if anything is not well-written.
Last edited on
Ok, this needs work.
line 1) you should not use language elements as variable names.
and line 2 is largely no good.

1
2
3
4
consider?
string foo{"hello world"};
stack_adt stack_variable{}; //empty stack
stack_variable.push(foo);  //stack_variable is 'filled' sort of.  It has one, of many possible, items in it now.  


it is common to use push to add an item to a stack and pop to remove it (these words). Everyone understands what these 2 words are. You can call it insert and remove or whatever, but it would be unusual to do so.

----------------------------
1
2
3
4
5
6
7
8
9
10
if you wanted to fill a string:
string foo{}; //empty
Input(foo); //a possible function could get data from the user and fill the string. 

example of the function:
void Input(string &s)
{
   cin >> s;
}


objects work just like integers as far as passing and returning them, except it is common to use references to avoid large copies as objects are bigger than integers and copying excessively is slow.
Last edited on
Note that C++ already has a stack container. http://www.cplusplus.com/reference/stack/stack/

If you want input, then a possible function could be like:

1
2
3
4
5
6
7
std::string inpStr() {
    std::string inp;

    // function body goes here

    return inp;
}


then used like:

 
const auto strInp{inpStr()};

Last edited on
> std::string string;
> string = Input(string);

Something like this (the function takes no arguments and returns a prvalue of type std::string), perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <string>

std::string Input()
{
    std::string string ; // this is fine as long as we don't have using namespace std ;
    std::cout << "enter a string: " ;
    std::cin >> string ;
    return string ;
}

int main()
{
    const std::string string = Input() ;
}

Topic archived. No new replies allowed.