Assignment operators in C + + and java

#include <iostream>
using namespace std;

class BankAccount{

private:
    double balance;

public:
    BankAccount(double openingBalance){//Initial balance
        balance = openingBalance;
    }

    void deposit(double amount){//Deposit money
        balance = balance + amount;
    }

    void withraw(double amount){//Withdraw money
        balance = balance - amount;
    }

    void display(){//Check the balance
        cout << "balance = " << balance << endl;
    }

};

int main()
{

    BankAccount bc1(200);
    BankAccount bc2 = bc1;
    bc1.withraw(21.00);
    bc2.withraw(21.00);
    bc1.display();
    bc2.display();

    return 0;
}

C + + program run result:

public class BankAccount {
    
    private double balance;

    public BankAccount(double openingBalance){
            balance = openingBalance;
        }

    public void deposit(double amount){
            balance = balance + amount;
        }

    public void withraw(double amount){
            balance = balance - amount;
        }

    public void display(){
            System.out.println("balance = "+balance); 
    
    }
    
    
    public static void main(String[] args) {
        BankAccount bc1 = new BankAccount(200);
        BankAccount bc2 = bc1;
        bc1.withraw(21.00);
        bc2.withraw(21.00);
        bc1.display();
        bc2.display();
    }
    
}

Java program run result:

Reason: in C + +

   BankAccount bc1(200);

This sentence creates an object and leaves room for all the object data

   bc2 = bc1;

Copy the data of bc1 object to bc2 object

The storage addresses of bc1 and bc2 are different

 

In Java

   BankAccount bc1 = new BankAccount(200);

This statement only creates a space to place the storage address of an object

   BankAccount bc2 = bc1;

bc2 copies the storage address that bc1 points to. In fact, they refer to the same object. Similar to references in C + +.

Tags: Java

Posted on Thu, 28 Nov 2019 10:32:05 -0800 by mithras