Skip to content

Instantly share code, notes, and snippets.

@Tevinthuku
Last active December 3, 2016 09:16
Show Gist options
  • Save Tevinthuku/62ffe30013a86729c158f83105cfe4d3 to your computer and use it in GitHub Desktop.
Save Tevinthuku/62ffe30013a86729c158f83105cfe4d3 to your computer and use it in GitHub Desktop.
Most of what you need to know about classes
// class examples
// author : Tevin Thuku
// Date: 3rd: Dec: 2016
class Square {
public:
double length;
double width;
};
int main( ) {
Square Square1;
Square Square2;
// square1 specification
Square1.length = 5.0;
Square1.width = 5.0;
// Square2 specification
Square2.length = 10.0;
Square2.width = 10.0;
// area of Square1
area = Square1.length * Square1.width;
cout << "Area of Square1 : " << area <<endl;
// area of Square2
area = Square2.length * Square2.width;
cout << "Area of Square2 : " << volume <<endl;
return 0;
}
// FRIEND FUNCTIONS
// FULL EXAMPLE
class Name {
string name;
public:
friend void printName( Name firstname );
void setName( string name );
};
// Member function definition
void Name::setName( string name ) {
name = name;
}
// Note: printWidth() is not a member function of any class.
void printName( Name firstname ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "My name is : " << firstname.name <<endl;
}
// Main function for the program
int main( ) {
Name firstname;
// set box width with member function
firstname.setName('ser arthur dayne');
// Use friend function to print the wdith.
printName( firstname );
return 0;
}
// destructors and constructors
// REFERENCED FROM TUTORIALSPOINT.. CONSTRUCTORS AND DESTRUCTORS
#include <iostream>
using namespace std;
class Line {
public:
void setLength( double len );
double getLength( void );
Line(double len); // This is the constructor
private:
double length;
};
// Member functions definitions including constructor
Line::Line( double len) {
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len ) {
length = len;
}
double Line::getLength( void ) {
return length;
}
// Main function for the program
int main( ) {
Line line(10.0);
// get initially set length.
cout << "Length of line : " << line.getLength() <<endl;
// set line length again
line.setLength(6.0);
cout << "Length of line : " << line.getLength() <<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment