Jump to content
Hash, Inc. Forums
robcat2075

C++ study group weekly discussion thread

Recommended Posts

Week 11

  • sizeof and Arrays
  • sizeof and multi-dimensional arrays (maybe)

 

Lets suppose you had a chain of linked sausages...

<====> <====> <====> <====> <====> <====> <====> <====>. . .

... but can't count them individually.

If you could know the length of the whole chain, and the length of the first sausage, you could divide the length of the chain by the length of the single sausage to know how many sausages there were... and how many buns you would need to get for them!

20 feet of 0.5 foot sausages would be 40 sausages.

 

That is basically how Steve Purcell is using sizeof with arrays.

if we declares an Array

int sausages[10];

we can use the sizeof function to examine it. We can use

sizeof(sausages)

to get how many bytes the whole array uses

and

sizeof(sausages[0])

to get how many bytes the first array element uses.

We can use those to get the length of the array and assign that to a variable

numberOfElements = sizeof(sausages)/sizeof(sausages[0])

We can use that variable later in For loops or other code that needs to know how long the array was.

 

Why did we need to figure out how many elements were in the array if we already put a number in when we declared the array?

Because later on, as we develop the program, or re-use it for something else we may change the number in that declaration but we won't have to go through the rest of the program to change all the code that uses the length of the array... we have made the code figure that out for us!

Share this post


Link to post
Share on other sites

Meeting tonight!

Share this post


Link to post
Share on other sites

Week 12

Switch. Switch uses a number you give it to choose from among several numbered cases

 

Sample project

  • Get the user to enter an integer up to 8 digits
  • Figure out how many digits the number is
  • use Switch  to  announce "This number has... digits"

Share this post


Link to post
Share on other sites

I got my digit-counter working so there will be a meeting tonight!

Share this post


Link to post
Share on other sites

Week 13

These next three sections are all related and are short so we'll take them together.

  • Functions let you put some frequently done task into a self-contained piece of code and then call it when you need it instead of having to explicitly write it out each time... AKA a "subroutine."
  • Return values give you information back from a function.
  • Function Parameters let you send information to a function.

Assignment: rework any past program to use a function or... invent anything else that uses a function!

 

Share this post


Link to post
Share on other sites

I'm enjoying the fact that I can now navigate around a C++ program without feeling completely** lost.  :)

 

 

**a little lost but not COMPLETELY.

 

Share this post


Link to post
Share on other sites

ok I think I'm at least 6 weeks behind :(

I need to get caught up this weekend. 

Share this post


Link to post
Share on other sites

Bring whatever you are on and we will eagerly look at it!

Share this post


Link to post
Share on other sites

I almost forgot... it's Thursday!

C++ Meeting tonight!

Share this post


Link to post
Share on other sites

Week 13b

We love functions so much we're holding them over for this week!

I'm disappointed you can't pass an array as a parameter to a function, but apparently the work-around for that is coming up with "pointers."

Share this post


Link to post
Share on other sites

C++ meeting Thursday night!

C you there!

typemock_comic_007.jpg

Share this post


Link to post
Share on other sites

We were talking about Rodney's "bubble sort" program and the question came up , why does it go through the array one more time after everything is sorted?

Here's a better explanation... during the swapping loop, the sorted flag gets set to false if any pair of array elements needed to be swapped in the array.

By the next-to-last pass, there is only one pair that needs to be swapped and after they are fixed, the array is correctly sorted. But since they did have to be swapped, the sorted flag still got set to false.

sorted true/false is the only info the swapping loop receives to know if it needs to run. It is only after it goes through the array one more time, and finds no pairs that need to be swapped that the sorted flag remains left at true, which prevents the loop from running again.

Share this post


Link to post
Share on other sites

Week 14

Prototypes and Headers

We know that a function is a subroutine that you can call from your main program. However the code for your function needs to appear in your source code file before the main{} loop or the compiler won't know what is being called and will fail.

Prototypes are a way around that

Suppose you have this function that takes a floating point value (inches) as a parameter, does some math on it and returns the new number (centimeters) as a floating point value...

float inchesConverted(float inches) {
    float centimeters = inches * 2.54;
    return centimeters;
}

 

Instead of having to put that at the beginning of my source code file I can move it to the end and put just a "prototype" in its place at the beginning...

float inchesConverted(float);

The prototype is just the name of the function, with the type of its parameters in the parentheses and the type of what it returns in front.  That is enough information for the compiler to get on with the rest of the program even though the real code of the function isn't encountered until after the main {} .

 

Headers... (TBC)

 

Share this post


Link to post
Share on other sites

Hey Paul...

C++14 is supposed to allow using a variable expression in the size of an array when you are declaring an array, and I see people showing sample code that does this but when i try it it doesn't work.

I'm not allowed to use anything other than an expression that evaluates to a constant as the size of an array..

Is there a way to do this?
 

// Concatenate arrays test.cpp :

#include <iostream>

int main()
{
    int X[] = { 1,2,3 };
    int Y[] = { 4,5,6 };

    int numX = sizeof(X) / sizeof(X[0]);// calc num elements in array X
    int numY = sizeof(Y) / sizeof(Y[0]);// calc num elements in array Y

    int arr[numX + numY];// make new array equal in length to X and Y combined. Error happenes here.
}

 

 

Share this post


Link to post
Share on other sites
On 9/7/2019 at 2:26 PM, robcat2075 said:

C++14 is supposed to allow using a variable expression in the size of an array when you are declaring an array, and I see people showing sample code that does this but when i try it it doesn't work.

I'm not allowed to use anything other than an expression that evaluates to a constant as the size of an array..

 

Apparently the solution is Vectors

https://www.geeksforgeeks.org/vector-in-cpp-stl/

A "vector" is like an array, it also has numbered elements, but it can be resized and added to during runtime and has many tools for managing it.
 

brief example...

#include <iostream>
#include <vector>

using namespace std;

int main()
{
	cout << endl << "VECTORS" << endl << endl;// title
  
	vector<int>myVector; // create a vector of ints
	myVector.resize(6);  // size it to have 6 elements

	myVector[5] = 298;   //assign a value to element 5
	cout << myVector[5] << endl<< endl; //print the value found at element 5

}

 

Share this post


Link to post
Share on other sites

C++ meeting tonight!

Prototypes and Headers (cont'd)...

The Prototype was a way to have a short form of a function at the top of your file and include the long-form elsewhere.

The Header is a way for that elsewhere to be a different file. It is also a way to incorporate clever bits by other programmers into your program without having to paste them into your main file.

Typically the header will contain only prototypes for functions... that are "implemented" in yet another file. But if you mention the header at the top of your main file, it all gets compiled somehow.

<iostream> is a "standard" header that adds common input/output function to C++

#include <iostream>

The actual iostream file that gets included by that looks very complex.

 

Share this post


Link to post
Share on other sites

Week 15

Classes are a way to bundle together different kinds of data that belong together into an "object". That will be useful since we are here to learn object-oriented programming!

For example, deep in A:M there might be a class for  CPs that has floating point numbers for X, Y and Z location and a boolean value for whether it is peaked or not, and a string for the name of the bone it is attached to.

A definition of that simple class might look like this
 

class ControlPoint {
public:
	float x;
	float y;
	float z;
	bool peaked;
	string bone;
};

That definition is just a template. You use your class name much like a variable "type" to declare instances
 

This code declares two instances of the class, named Fred and Barney.

ControlPoint Fred;

ControlPoint Barney;

 

Each one has its own set of data variables inside it and you access them via the instance's name.
 

Fred.x = 10.5; // sets the Fred CP's X to 10.5

Barney.bone = "Upper Arm"; // sets the Barney CP's bone string to "Upper Arm"

 

Share this post


Link to post
Share on other sites

Here it is... my first c++ graphic.

It's called "Projectile Against the Wind"

projectile.png

 

I'm working through "The Ray Tracer Challenge" which purports to teach you how to write a ray tracing renderer.

While doing this I have encountered a C++ mystery which i will show at our next meeting.

Share this post


Link to post
Share on other sites

The buggiest part of Microsoft Visual Studio is the survey that comes up to ask me how bad the bugs are in Microsoft Visual Studio.  🤨

Share this post


Link to post
Share on other sites

Thing to remember to not do in Visual Studio...

Do not try to copy and paste files from one "project" to another. It is not like copying and pasting files in Windows folders.

 

After I had my project 31a Classes working (see below), it would have been convenient to copy the files from that source folder to the source folder for a new project 32a Classes data members and continue experimenting with new stuff.

That only appears to work. The "copied" files are not copies, they seem to be merely aliases to the originals. Anything you change or rename in the new project will also be changed in the project they came from, probably breaking it and maddening to fix.

deleteClasses.JPG

 

Instead, after you "Add" a new project to your "Solution", "Add" new generic files with new names as stand-ins, then manually copy and paste the code from the windows of the old project to the windows of the new Project.

Share this post


Link to post
Share on other sites

Meeting Friday night at 10:15PM CDT!

Share this post


Link to post
Share on other sites

Week 16

Classes with getters and setters

Here is an example of an class I made while going through the ray-tracing book. Ray tracing has lots of things described by locations in XYZ space, among which are "points" and "vectors".

They can both be stored as an object called a "Tuple" which contains data members for X Y Z .  It also has W which flags whether it is a point or a vector.

There is a custom constructor that takes four parameter values to set X Y Z W values when the tuple is created.

The setValues method takes the same four parameters but is called on a Tuple that already exists.

This Tuple class also has methods for operating on its data.

For example, a "dot product" of two tuples is something ray tracing wants. Instead of writing a function that needs six parameters (the X Y Z values for one Tuple and the XYZ  for the second tuple), I make a method called dotWith in this class.

Becasue it is in this class it will know the XYZ values for the current tuple and I can pass it an "other tuple" for the other XYZ values it needs to do the calculations.
 

class Tuple
{
public:
	// data members, default values...
	float x = 0;
	float y = 0;
	float z = 0;
	float w = 1;// 1 make this a point, 0 makes this a vector;

	//constructors and deconstructors...
	Tuple();
	Tuple(float x, float y, float z, float w);
	~Tuple();

	// methods...
  	void setValues(float x, float y, float z, float w)
      
	float TupleOperation(char op, float x, float y, float z, float w);
	Tuple addedTo(Tuple addend);
	Tuple scaledBy(float);
	void printValues(string title);
	Tuple multiplyBy(Matrix4x4 transform);

	float dotWith(Tuple otherTuple);// returns Dot product 

	Tuple subtract(Tuple otherTuple);

private:	
};

 

The above is just the "declarations"

The actual code that gets executed for the dotWith method looks like this, and is else where in the program file ...
 

float Tuple::dotWith(Tuple otherTuple) {

    float dotProduct = this->x * otherTuple.x + this->y * otherTuple.y + this->z * otherTuple.z;
    return dotProduct;
}

 

Share this post


Link to post
Share on other sites

Here's another C++ mystery.

 

This class "Tuple" has x y z w as "private" variables that are only accessible to methods in an instance of this class.

However, when the method "dotWith" is passed another Tuple as a parameter, it is able to directly access the x y z w in that other Tuple directly.

 

// PublicPrivateTest_B.cpp 

#include <iostream>
using namespace std;

class Tuple {
private:
	float x = 0;
	float y = 0;
	float z = 0;
	float w = 1;

public:
	
	Tuple() {};
	//custom constructor to load values upon creation...
	Tuple(float x, float y, float z, float w) {
		this->x = x;
		this->y = y;
		this->z = z;
		this->w = w;
	};
	~Tuple() {};

	// one method to test them all
	float dotWith(Tuple otherTuple) {
		float dotProduct = this->x * otherTuple.x + this->y * otherTuple.y + this->z * otherTuple.z;
		/*why does the above line work,
		with direct calls to private data members 
		of another object, like "otherTuple.x" ?
		I expected it to fail after I moved x y z w 
		from "public" to "private"*/

		return dotProduct;
	};
};

int main()
{
	Tuple firstTuple(4, 3, 2, 1);
	Tuple secondTuple(5, 6, 7, 0);

	cout << "dot product: " << firstTuple.dotWith(secondTuple) << endl;

	//if uncommented,the direct call to x in the next line will fail, as expected...
	//cout<< "secondTuple.x: "<< secondTuple.x<<endl;

	return 0;
}

 

Share this post


Link to post
Share on other sites
On 10/14/2019 at 11:11 PM, robcat2075 said:

Here's another C++ mystery.

This class "Tuple" has x y z w as "private" variables that are only accessible to methods in an instance of this class...

After some inquiries on the web it seems that it is normal and expected that if two objects are born of the same class, a method in one can see and access the "private" data  in another.

To me that seems like a giant loophole but no one questions it.

 

In other news, the most recent update to Visual Studio seems to have added highlighting of escape sequences in strings. Notice how the "\t" ( for a tab) is a different color.

A good reason to update.

image.png

Share this post


Link to post
Share on other sites

It's good to read through older posts from time to time.

I just saw the one where Roger had spotted the one pass Bokeh effect.

It seems familiar but I have no recollection of reading that post previously.

Interesting.

 

In other news:  I spotted (and now have used) a method of video screen capturing. 

I currently have it set up to run via batch file to capture approx 2 minute quick draw sketching sessions.

I'd now like to investigate turning it into a more solid c++ driven utility. 

In the interim I hacked the batch file into an .exe file via a randomly downloaded batch to exe application.

The settings for now mostly have to be ran at the outset and not interactively but the FPS and duration can be set and it can target specific windows or the entire desktop.  For good measure I made the MP4 video output intially have a static name (so the most current output can be targeted by other applications but then also datetimestamp copies so each is preserved when the capture is launched again. After the storage of the capture I then have it played back for the user to see.   

For use with A:M, say to record video tutorials the primary thing needed after the recording would be determining how best to crop the image to leave out say... the icons at the bottom of the screen.  The recording size (even over multiple monitors) can be customized; that size initiates from the top left corner of the screen(s).

 

 

 

 

Share this post


Link to post
Share on other sites

C++ meeting tonight!

Share this post


Link to post
Share on other sites

It just dawned on me...

In Visual Studio... Edit>Advanced>Format Selection  lists Ctrl+K, Ctrl+F as the keyboard shortcut.

Those aren't options... you have to do them both in that order!

D'oh!

 

 

Share this post


Link to post
Share on other sites

Illustration of the difference between  while and do-while

 

main-qimg-4175b57d9850b90bd71ad1d22d8f30

Share this post


Link to post
Share on other sites

C++ meeting tonight!

Share this post


Link to post
Share on other sites

Here's an unnecessary program i made tonight. It composes music!

 

 

image.png

 

Share this post


Link to post
Share on other sites

Here's a handy debugging tool...

RMB on an object name>Find all references will show you a list of every use of that name including a bit of context as to what is being done to it.

Clicking on any instance in the list takes you to the right place in the code, even if you have it in multiple files in the Project.

image.png

Share this post


Link to post
Share on other sites

C++ meeting tonight?

Share this post


Link to post
Share on other sites

Here is a little bit done with Classes.

I made one class for an Alien that stores its X and Y location as integers and its graphics characters as strings.

Then it has two methods. One updates the alien's position  by incrementing  the location values in the class. The other prints the strings to wherever those locations are.

Once that class is made, an array of them can be deployed and each one keeps track of its own location as the update and print methods are called in a loop.
 

while (true) {

        for (int i = 0; i < NUM_ALIENS; i++) { //cycle through all the aliens in the array

            alien[i].updateAlien();
            alien[i].printAlien();
        }
  
        sleep_until(system_clock::now() + 0.100s); //delay 1/10th second
    }

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...