Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ constructor not working

This is my makeAccount.cpp:

#include "account.h"
#include <string>
using namespace std;

int makeAccount::getAccountNumber()
{
    return accountNumber;
}

double makeAccount::getAccountSaldo()
{
    return accountSaldo;
}

string makeAccount::getName()
{
    return name;
}

makeAccount::makeAccount(std::string naam, int id, double saldo)
{
    naam = name;
    id = accountNumber;
    saldo = accountSaldo;
}

this is my makeAccount.h

#include <string>
#include <sstream>

class makeAccount
{
public:
    makeAccount(std::string naam, int id, double saldo);
    int getAccountNumber();
    double getAccountSaldo();
    std::string getName();
private:
    int accountNumber;
    double accountSaldo;
    std::string name;
};

this is my main.cpp

#include "account.h"
#include <iostream>
using namespace std;

int main()
{
    makeAccount::makeAccount test("test", 30,  23.5);
    cout << test.getName() << endl;
    cout << test.getAccountNumber() << endl;
    cout << test.getAccountSaldo() << endl;
    return 0;
}

Now I have the following problem, when I try to execute this code I get this: 1606416736 6.95322e-310 I think there is a problem in my account.h where I declare the constructor but I can't figure out what exactly is the problem. However when I do something like this:

private:
    int accountNumber = 1234;
    double accountSaldo = 1;
    std::string name = "test";
};

It does work, so I think i either way have something wrong in my constructor or where in my makeAccount.cpp where I have this code:

makeAccount::makeAccount(std::string naam, int id, double saldo)
{
    naam = name;
    id = accountNumber;
    saldo = accountSaldo;
}

Thanks in advance.

like image 374
that guy Avatar asked Nov 23 '25 19:11

that guy


1 Answers

You have your assignments reversed.

You'll want this:

makeAccount::makeAccount(std::string naam, int id, double saldo)
{
    name = naam;
    accountNumber = id;
    accountSaldo = saldo;
}

Normally you'd want to use an initialization list, your constructor should look like this:

makeAccount::makeAccount(std::string naam, int id, double saldo) :
  accountNumber(id),
  accountSaldo(saldo),
  name(naam)
{}
like image 127
nos Avatar answered Nov 26 '25 08:11

nos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!