-3

I want to write a code that will accept input but store it as private in C++ but I keep getting a weird output after compiling it. Below is my code

#include <iostream>
#include <string>

using namespace std;

class MyClass{
    private:
        int salary;
        
    public:
        string fname;
        string lname;
        int age;
        
        void sent(string fname1, string lname1, int age1){
            cout<<"My name is "<<fname1<<" "<<lname1<<" and i am "<<age1<<" years old.";    
        };
        
        void setSalary(int s){
            salary = s;
        }
        
        int getSalary(){
            return salary;
        }
};

int main(){
    
    MyClass myObj;
    
    
    string fname2 = myObj.fname;
    string lname2 = myObj.lname;
    int age2 = myObj.age;
    int salaries;
    myObj.setSalary(salaries);
    
    cout<<"Enter first name: ";
    cin>>fname2;
    
    cout<<"Enter last name: ";
    cin>>lname2;
    
    cout<<"Enter age: ";
    cin>>age2;
    
    cout<<"Salary amount: ";
    cin>>salaries;
    
    myObj.sent(fname2, lname2, age2);
    cout<<"\n";
    
    myObj.getSalary();
    
    return 0;
}
kuro
  • 3,214
  • 3
  • 15
  • 31
Elridder
  • 1
  • 2
  • 4
    "keep getting a weird output" – it would help if you included the output – kirjosieppo Jan 12 '22 at 12:11
  • Welcome to Stack Overflow. Please read [ask] and https://meta.stackoverflow.com/questions/359146. We can only explain error messages that you actually show to us. – Karl Knechtel Jan 12 '22 at 12:12
  • 2
    `myObj.setSalary(salaries);`. Here `salaries` is uninitialized. So, `myObj.getSalary()` will result in unexpected output as expected. You should use `cin` to get salary from user and then call `setSalary()` – kuro Jan 12 '22 at 12:12
  • Also where is your class constructor? – sagi Jan 12 '22 at 12:14
  • You do things in a weird way and in a weird (and wrong) order. For example, why do you initialize `fname2` and `lname2` with the default-constructed (and empty) `myObj.fname` and `myObj.lname` variables? That doesn't make any sense. What resource are you using to learn C++? Perhaps you should consider some other resource? [Here's a list of good books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), I recommend you invest in a couple of the beginners books. – Some programmer dude Jan 12 '22 at 12:33

1 Answers1

0

You should call

    cout<<"Salary amount: ";
    cin>>salaries;

before

    myObj.setSalary(salaries);

and also actually print the salary you get:

    cout << myObj.getSalary();
kirjosieppo
  • 617
  • 3
  • 16