Why don't I get any output?

123 Views Asked by At

I am trying to write my first OOP code in C++, but for some reason I am not getting any output. I am trying to create a class that contain a method getSquare() that accept an int n and returns the number squared. Can anyone tell me where I am doing wrong?

#include <iostream>

using namespace std;

class myClass {

public:
    int square;    
    void getSqure(int n);  
};

void myClass::getSqure(int n) {
    int square = n * n;
}

int main(){
    int n = 5;
    myClass c;

    c.getSqure(5);

    cout << endl;
    return 0;
}
2

There are 2 best solutions below

4
vsoftco On BEST ANSWER

Your getSquare function doesn't do anything, but just defines the variable square (does not return it though). Make it return it as an int, like

int myClass::getSqure(int n) { // make sure to change the declaration also
    int square = n * n;
    return square;
}

then do

cout << c.getSquare(5) << endl;

and you'll have an output.

0
Austin Staab On

This is how I interpreted the code while trying to stay as close as I could to the original rules of your question.

#include <iostream>
#include <conio.h>

int main()
{
    class MyClass
    {
    public:

           int Number;
           int Square;
    };

    MyClass N;

    std::cout << "Please enter a number." << std::endl;
    std::cin >> N.Number;
    std::cout << std::endl << std::endl;

    std::cout << "Original number: " << N.Number;
    std::cout << std::endl << std::endl;

    N.Square = (N.Number * N.Number);

    std::cout << "Squared number: " << N.Square;
    std::cout << std::endl << std::endl;

    std::cout << "Press any key to continue.";

    _getch();
    return(0);
}

Output:

Please enter a number. 5

Original number: 5

Squared number: 25

Press any key to continue.