r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

Show parent comments

1

u/[deleted] Apr 05 '22

[removed] — view removed comment

4

u/plastikmissile Apr 05 '22

I'm going to use C# syntax (because my C++ is rusty) but I'm sure it will be clear enough.

First let's do things without static.

public class Math
{
    public int Add(int x, int y)
    {
        return x+y;
    }
}

public class Main
{
    public void DoSomething()
    {
        var mathInstance = new Math();
        var result = mathInstance.Add(10,20);
    }
}

As you see, to use Add we have to create a new instance of Math which we called mathInstance and then used that to access Add. Looking at the code for method Add you'll see that it only uses its inputs and nothing else. For all intents and purposes to Add the class Math may as well not exist.

So now let's do it the better way, and use static.

public class Math
{
    public static int Add(int x, int y)
    {
        return x+y;
    }
}

public class Main
{
    public void DoSomething()
    {            
        var result = Math.Add(10,20);
    }
}    

Note how we didn't need to instantiate Math at all, and just used Add directly. This only works because Add doesn't need access to any information in the instance.

If for instance the class Math looked like this instead:

public class Math
{
    private int z;

    public int Add(int x, int y)
    {
        return x + y + z;
    }
}

We wouldn't be able to make Add static, since it also uses z which is part of the instance. Unless you make z static as well.

ETA: Don't copy/paste while you are learning. It's OK to look up code, but type it in yourself. This way you force your brain to think about what it's doing, and thus learn.